How to bind Lightbox popups to images loaded via AJAX

| | 1 min read

AJAX is now widely used in to web development to make the user interfaces simpler and faster. We may use AJAX to load images after page load in order to increase performance. However if you want to have a lightbox popup with the full image bound to an image loaded by AJAX then you might run into problems. You will find that even after linking the JS, CSS files and adding the rel="lightbox" attribute to the images it might not work.

Light-box adds the onclick() event for the images with lightbox rel attribute at page load. This onclick event is what opens the lightbox. Since you are loading the images after page load the click events will not get attached to the images. That is why the full sized images don't open up in Lightbox.

Here is your lifesaving solution - just call the initLightbox() JS function just after you are done with your AJAX request that loads the images. The logic is as simple as this as initLightbox() is the lightbox function that adds the onclick event to the images. Alternatively you can use the jQuery function $.getScript() and add it to your js; use it to load the lightbox2/js/lightbox.js file, which in turn is same as loading the entire light-box script again.

If you had changed the js as per the direction, just reload your page and enjoy the beauty of lightbox image, that too AJAX loaded!.