Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add jQuery colorbox plugin to a dynamically created element

The usual way to assign color box functionality on a link is like this:

$("a.colorbox").colorbox({ transition: "elastic" });

Newly added items are not bound in this way though.

How can I add colorbox to dynamically created

<a class="colorbox"></a>
elements too?

like image 213
Jon Winstanley Avatar asked Mar 14 '10 19:03

Jon Winstanley


2 Answers

The method described here is to live-bind to the click event on the elements you're interested in (such as .colorbox in this instance) and call the colorbox library function in the handler:

$('.colorbox').live('click', function() {
  $.colorbox({href:$(this).attr('href'), open:true});
  return false;
});
like image 133
James Kolpack Avatar answered Nov 06 '22 17:11

James Kolpack


You could also try this:

$('.colorbox').live('click',function(e){
    e.preventDefault();
    $(this).colorbox({open:true});
});

I think it's a little cleaner then using the fn command.

like image 18
simonthetwit Avatar answered Nov 06 '22 15:11

simonthetwit