Tuesday, January 27, 2009

[jQuery] Re: Event delegation and hover(over, out)

The way the post initially reads, it seems that when you're appending
the ul with an li, the anchor within it does not have the click
function bound to it. Is that correct? If so, when you add the li you
would need to bind the click function to the newly created anchor.
Something like this should do the trick:

$("ul.removable").append('<li><a href="#">1<img style="display: none;"
src="icon_remove.gif" /></a></li>');
$("ul.removable li:last a").bind("click", function()
{
$("img", $(this)).fadeIn("fast");
}, function()
{
$("img", $(this)).fadeOut("fast");
});

On Jan 26, 5:59 am, Steffen Wenzel <steffen.wen...@dasframe.de> wrote:
> Hi,
>
> 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: