lokesh / lightbox2

THE original Lightbox script (v2).
http://lokeshdhakar.com/projects/lightbox2/
MIT License
6.22k stars 1.77k forks source link

Extra #lightbox elements when reloading page with ajax #517

Closed jpardi closed 6 years ago

jpardi commented 8 years ago

In my site, my images are loaded via ajax. Two things I have found:

  1. Once the page loads, I must call lightbox.init() for the plugin to do its magic. Is calling init() correct in this use case?
  2. When repetitively refreshing the images, lightbox creates a #lightbox element upon each ajax call. This causes a problem in that an empty lightbox appears in the page after the second ajax call. To fix this, I modified the build() function as below, which seems to fix the problem.
var lbox = $('#lightboxOverlay');
if (lbox[0] == undefined) {
    $('<div id="lightboxOverlay" class="lightboxOverlay"></div><div id="lightbox"  ....... </div>').appendTo($('body'));
}

Does this make sense? If so, can this fix be incorporated into the master code?

NaiDev commented 8 years ago

Hi, how do I implement that piece of code into my js file?

timkingman commented 8 years ago

I hit a similar issue trying to upgrade from 2.51 to 2.8.2. I still had the lightbox script included in the head, which meant the init method was running before I even had any page content at all. The docs tell you to add the lightbox script at the end of body, which fixes this issue. The click handlers are attached to body, so you don't need to run init() again after loading ajax content.

My patch recommendation would be to defer init() to run after the dom loads, which used to happen in a $(function(){ } ) block at the bottom of 2.51, but runs on script load in 2.8.2.

leiz-me commented 7 years ago

Same issue. Using the trick that @jpardi provided to make it work.

lokesh commented 6 years ago

Chiming in on this older issue.

If anyone else is seeing this issue they can call lightbox.enable() instead of lightbox.init(). The enable method attaches the click events to the newly added images but does not construct any new DOM elements to append to the page.

In the next release I'll be adding a code check to prevent the duplication of the DOM elements. Multiple init() calls will not cause any side effects.

https://github.com/lokesh/lightbox2/pull/615

lokesh commented 6 years ago

Resolved: https://github.com/lokesh/lightbox2/releases/tag/v2.10.0