francoischalifour / medium-zoom

🔎🖼 A JavaScript library for zooming images like Medium
https://medium-zoom.francoischalifour.com
MIT License
3.65k stars 165 forks source link

is possible initialize dynamically? #24

Closed KsCorrales closed 6 years ago

KsCorrales commented 6 years ago

I generate images dynamically because I am doing a SPA but the zoom does not work.

francoischalifour commented 6 years ago

You need to attach the zoom to each image added to the DOM. The lib is not observing the DOM for changes.

If I miss your point, please explain further.

KsCorrales commented 6 years ago

okay i resolve the problem, i use jquery "live on"

$('body').on('DOMNodeInserted', '[data-action="zoom"]', function () {
    mediumZoom('[data-action="zoom"]');
});

but now i have a problem, the plugin create an image at the bottom of the code ok good, but when i out zoom and i open zoom again, create 2 images in the dom and to close y need 2 clicks out of image, when close i click again and create 3 images elements and so on :S

francoischalifour commented 6 years ago

That's because you're applying the zoom multiples times on the same images. You should check beforehand if the image has the medium-zoom-image class.

mediumZoom(
  Array.from(document.querySelectorAll('[data-action="zoom"]'))
    .filter(img => !img.classList.contains('medium-zoom-image'));
);

A better way to do it would be to use the event target of the DOMNodeInserted callback:

document.body.addEventListener('DOMNodeInserted', function (event) {
  mediumZoom(event.target);
});

This is plain JavaScript (see reference), it should work with jQuery as well.

Hope it helps!