Yep, that’s pretty ugly code. 🙂
First, you only need to include $(document).ready(function(){ ... });
once. Put everything inside it, where I put the ...
.
Second, the neat thing about jQuery is that you can really easily “get” lots of elements at once as long as they share something unique to them — like they all have the same class, or are all <img>
elements.
ALSO, avoid writing accented letters in your HTML; write HTML entity names instead, because otherwise they won’t show up properly on many browsers. For example, write ñ
instead of “ñ”. (See here: http://www.w3schools.com/tags/ref_entities.asp)
Here’s an easy fix:
-
In your HTML, give each of the
img
a “title” attribute with whatever you want the “busca por” to say when theimg
is mouseovered. For example:<li><a href="https://stackoverflow.com/" id="laticinios"><img src="i/ingredientes_02.gif" title="laticiños" /></a></li>
-
Replace your JS/jQuery code with this:
$(document).ready(function(){ $("#ingredientes ul li a").hover( //This activates when any "a" element in a "li" element in a "ul" element in an element with the id of "ingredientes" is mouseovered function(){ var foodType = $(this).children("img").attr("title"); //This "gets" the value of the "title" attribute of each of the `img` tags and makes it a variable called "foodType" $("#old").text(foodType); }, function(){ $("#old").text("ingrediente"); } ); });
I think that’ll work.
1
solved Jquery hover function – how to make this simple?