pawelgrzybek / siema

Siema - Lightweight and simple carousel in pure JavaScript
https://pawelgrzybek.github.io/siema/
Other
3.49k stars 408 forks source link

Using loop in siema, click events are forgotten #268

Closed simplenotezy closed 4 years ago

simplenotezy commented 4 years ago

It seems as though Siema will duplicate divs when setting loop to true. I have discovered that in such case, my click event that is attached to the slide element is not present on all the duplicated slides.

I used this piece of code in the console to narrow down, why my click events were not being registered inside some the slide div element:

for(let element of document.getElementsByClassName('show-gallery-image')) { console.log(getEventListeners(element)); }

It logs 12x empty object, 6x click events, and 12x empty objects again for a slider with 6 slides.

I am not sure why DOM elements are repeated so many times, but perhaps it has something to do with my setup. I also wrote about that here: https://github.com/pawelgrzybek/siema/issues/266

What can I do to ensure click event handlers are also copied to the cloned divs?

simplenotezy commented 4 years ago

I guess the solution is to use onClick since this will be cloned.

https://stackoverflow.com/questions/15408394/how-to-copy-a-dom-node-with-event-listeners

pawelgrzybek commented 4 years ago

Unfortunately loop options requires duplications to achieve smooth experience. You are right, event listeners will be attached only to the original objects, not to clones. You can read about event delegation, that may solve your problem. Another resource to help you with your problem is:

https://pawelgrzybek.com/cloning-dom-nodes-and-handling-attached-events/

Hopefully that helps 👋

simplenotezy commented 4 years ago

Cool thanks. I instead just attached the listener on init and on the class, instead of directly on the element 😊