0

I'm adding a button dynamically depending on div existence, so I have this:

function addVideoButton(id) {
    var div = document.createElement('div');
    div.className = 'video';
    div.dataset.videoid = id;
    div.dataset.params =     "modestbranding=1&am;showinfo=0&vq=720&color=white&theme=light&fs=1"
    div.innerHTML = '<button class="play c-btn"><use xlink:href="#play"></use>WATCH VIDEO</button>';
    var title = findTitle();
    document.getElementById(title).appendChild(div);
}

Also, I have the below piece so when these types of buttons are clicked, a param is taken (video id) and then a video is played on a modal

// show frame for the video modal
    $(this).find('.play').on("click", function() {
      showFrame(getIframe(videoId, params), "video");
    });

However, I noticed that if I add the button dynamically as above, then click event binding won't work, if I clicked, it won't start the modal, what am I missing?

John R
  • 207
  • 3
  • 13

2 Answers2

0

Kindly use below code to bind click to dynamically added containers. Any elemnt which come in future in the DOM should be binded to event like below.

$("body").on("click",".play", function() {
      showFrame(getIframe(videoId, params), "video");
    });
amit wadhwani
  • 1,110
  • 1
  • 5
  • 12
0

You need to add the event to one of the parent elements of the button, that is present at the time the document was loaded. The event bubbles up and will be caught. In your case, your entire <div> is dynamically added, so adding an event handler to the immediate parent to this <div> should work.

Silencer310
  • 690
  • 2
  • 6
  • 24