Well, in a way the Spanish did hold off the Ottoman advance in the Mediterranean. The Ottomans failed to conquer southern Italy, and Charles V halted the Ottoman invasion of Hungary and Austria.
However you probably mean a Spanish conquest of the Maghreb, or at least a defeat of the Barbary pirates. In that case, you have to go back in time and prevent the Habsburgs from inheriting the Spanish crown. Central European drama will only drag Spain down and distract it from its Mediterranean goals. There was also the Treaty of Alcáçovas in 1479, which gave the Moroccan sphere of influence to Portugal.
Prevent Habsburg Spain, and have Portugal deed North Africa to Spain (perhaps with the Spanish agreeing that the rest of Africa is under Portugal's sphere of influence) and the Kingdom of Spain under the Trastámara dynasty has a significant chance of keeping the Ottomans out of the Maghreb and possibly conquering Morocco.