I’m dealing with jquery selector.
I have a portion of html that (simplified) looks like
<div class="tile">
message
<a href="#" class="ui-icon ui-icon-pencil">link1</a>
<a href="#" class="ui-icon ui-icon-close">linkb</a>
</div>
this div is repeated severl times in the page
and in the relative javascript I want to add the code to show or hide the 2 links when the user pass the mouse over the “tile” div.
I wrote something like
$(function () {
$(".tile").bind("mouseover", function () {
$("this .ui-icon").show();
});
$(".tile").bind("mouseout", function () {
$("this .ui-icon").hide();
});
});
but this doesn’t work.
Anyone can help me here?
Several options:
Minimal fix
You’ve used “this” within the selector; what you want to do is use
$(this)to get a jQuery object for the actual tile the mouse moved over, and then usefindto find the descendant elements. You’re also better off usingmouseenterandmouseleavethanmouseoverandmouseout:(The reason you’re better off is that
mouseoverandmouseoutbubble, and so as the mouse travels over descendant elements of the “tileAgenzia” elements, you’ll see messages from those descendants.)Use CSS (if you can)
But it’s worth noting that unless you have to support IE6 and IE7 (and some people do), you can do this purely with CSS, no JavaScript required:
When the mouse is hovering anywhere over an element with the class “tileAgenzia”, its descendant elements with the class “ui-icon” will be visible; when the mouse isn’t hovering over it, they won’t.
More concise jQuery
If you want to stick with the JavaScript solution, you can use the
hoverfunction, which is (if you pass it two functions) just a shortcut for hooking upmouseenterandmouseleave: