Search code examples
javascriptjqueryiconstoggleclone

Why is toggle icon not working after cloning div?


Basically, I'm working with three tabs called 'Monday', 'Tuesday' and 'Favorites'. I have a toggle icon which is a heart. If I'm in Monday and click on the icon the empty heart turns to be filled out and it's cloned and added to the '#fav' tab. From the moment it gets there the toggle icon doesn't work at all.

I've tried:

clone(true, true)

but doesn't seem to be working well for me. I know something's wrong, so I would appreciate if someone could point me in the right direction.

I've created this fiddle, so you can experience the issue.

https://jsfiddle.net/itsfranhere/nbLLc3L0/15/


Solution

  • Event listeners are not attached to the elements which created dynamically. Hence, the click event is not fired for elements in favorites tab.

    Either you need to attach event listener to the anchor elements in fav tab or use event propagation to capture the event.

    $('div.tab-pane').on('click', '.favorite', function(e) {
     // code here
    }