I'm appending elements to a list and want to attach a hover-event
(show or hide image) to links inside of that list-element. The HTML
ist:
<ul class="removable">
<li><a href="#">1<img style="display: none;" src="icon_remove.gif" /
></a></li>
<li><a href="#">2<img style="display: none;" src="icon_remove.gif" /
></a></li>
<li><a href="#">3<img style="display: none;" src="icon_remove.gif" /
></a></li>
<li><a href="#">4<img style="display: none;" src="icon_remove.gif" /
></a></li>
</ul>
And here is the jQuery:
$("ul.removable li a").hover(
function(){
$('img', this).fadeIn("fast");
},
function(){
$('img', this).fadeOut("fast");
}
);
Works like a charm. Until I add list-elements. The most elegant way to
work around that seems to be event delegation, which I was able to use
when removing
list-elements:
$("ul.removable").click(function(event){
if($(event.target).parent().is('li'))
$(event.target).fadeOut("fast");
return false;
});
Now the question: How does this work with hover(over, out)? It should
have been something like:
$("ul.removable").hover(
function(event){
if($(event.target).parent().is('li'))
{
$(event.target).children().fadeIn("fast");
}
},
function(event){
...
}
);
But it just notices that I'm hovering the unordered list. I'm now
thinking that event delegation simply doesn't work with hover and came
up with this
(thanks to jQuery 1.3.1):
// show "remove me"-Icons (attached with .live)
$("ul.removable li a").live("mouseover",
function(){
$('img', this).fadeIn("fast");
}
);
// show "remove me"-Icons (attached with .live)
$("ul.removable li a").live("mouseout",
function()
{
$('img', this).fadeOut("fast");
}
);
I'm eager to learn how to write more elegant and simple jQuery, so:
Any improvements?
Thanks, Steffen
No comments:
Post a Comment