Karem
Karem

Reputation: 18103

jQuery: using live() with each()

I have this function here:

$("a.fancybox_vid").each(function(){
   $(this).fancybox({
    titleShow     : false,
    width:    640,
    height:   395,
    autoDimensions: false,
    overlayOpacity: 0.6,
    href: "misc/mc.php?v="+$(this).attr('id')
  }); 
});

Now a link with c lass .fancybox_vid gets appended, and then this will not work. Only if it is there from the beginning. How can I have live() in this each().

Upvotes: 8

Views: 12575

Answers (3)

Eivind
Eivind

Reputation: 841

What about doing a live event, that calls the fancybox:

$("a.fancybox_vid:not(.fancy)").live('click', function(){
 $(this).addClass('fancy').fancybox({
  titleShow     : false,
  width:    640,
  height:   395,
  autoDimensions: false,
  overlayOpacity: 0.6,
  href: "misc/mc.php?v="+$(this).attr('id')
 }); 
});

Upvotes: 0

user113716
user113716

Reputation: 322562

If you want "live-like" functionality for methods, you can use the livequery plugin:

$(function() {
    $('a.fancybox').livequery(function() {
        $(this).fancybox({
            titleShow     : false,
            width:    640,
            height:   395,
            autoDimensions: false,
            overlayOpacity: 0.6,
            href: "misc/mc.php?v="+$(this).attr('id')
        });
    });
});

...although it would be better (less overhead) to just call the fancybox plugin on the newly created elements.

Upvotes: 4

Harmen
Harmen

Reputation: 22436

This is not possible, as live handles events. Fancybox only creates events on the current element queue.

I think you have to apply the .fancybox() method every time you create a new element.

Upvotes: 0

Related Questions