Trigger lightbox with javascript

XCS picture XCS · May 30, 2012 · Viewed 7.5k times · Source

I want to use this library: http://lokeshdhakar.com/projects/lightbox2/

I can't attach rel="lightbox" to each image so I want to use jQuery to trigger the lightbox.

I was thinking about something like:

$('img').click(function(){
  //triger lightbox for this image
  //use self src as href
});

How can I trigger the lightbox for one image?

Answer

XCS picture XCS · May 30, 2012

Solved the problem by wrapping the img tag in an a tag and triggering click on a after that.

$('img').click(function () {
    $(this).wrap('<a href="' + $(this).attr("src") + '" rel="lightbox" />');
    $(this).parent('a').trigger('click');
});