0

I am appending a div to body using query for modal and button is associated with modal. I am trying to close the modal using button and my code is following. it looks like issue with event triggering.

 $('a.launch-youtube-modal').click(function(event) {
      event.preventDefault();
      $('body').append([
        '<div class="youtube-modal">',
          '<div class="youtube-modal-container"><div class="youtube-modal-video-container">',
         '<iframe width="671" height="495" src="'+ $(this).attr('href') +'" frameborder="0" allowfullscreen id="youtube-video"></iframe>',
         '<button class="ss-icon ss-gizmo youtube-close">close</button>',
          '</div></div>',
        '</div>'
      ].join(''));

 function closeYoutubeModal() {
        if (!video) return;
        video.jQYT('destroy');
        $('.youtube-modal').remove();
      }
      $('.youtube-modal .youtube-close').click(function () {
         closeYoutubeModal();    
      });
    });
Nisarg
  • 1,631
  • 6
  • 19
  • 31

2 Answers2

1

Try this: use .on for binding click event handlers for dynamically created elements. you can keep close button click handler outside modal click handler

$('a.launch-youtube-modal').click(function(event) {
      event.preventDefault();
      $('body').append([
        '<div class="youtube-modal">',
          '<div class="youtube-modal-container"><div class="youtube-modal-video-container">',
         '<iframe width="671" height="495" src="'+ $(this).attr('href') +'" frameborder="0" allowfullscreen id="youtube-video"></iframe>',
         '<button class="ss-icon ss-gizmo youtube-close">close</button>',
          '</div></div>',
        '</div>'
      ].join(''));

 });

function closeYoutubeModal() {
   if (!video) return;
   video.jQYT('destroy');
   $('.youtube-modal').remove();
}
$(document).on('click','.youtube-modal .youtube-close',function () {
    closeYoutubeModal();    
});
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

The working:

$('a.launch-youtube-modal').click(function(event) {
      event.preventDefault();
      $('body').append([
        '<div class="youtube-modal">',
          '<div class="youtube-modal-container"><div class="youtube-modal-video-container">',
         '<iframe width="671" height="495" src="'+ $(this).attr('href') +'" frameborder="0" allowfullscreen id="youtube-video"></iframe>',
         '<button class="ss-icon ss-gizmo youtube-close">close</button>',
          '</div></div>',
        '</div>'
      ].join(''));

 });

 $('body').on('click','.youtube-close', function() {
        console.log("Youtube modal closed");
        $('.youtube-modal').remove();
      });
    });
Nisarg
  • 1,631
  • 6
  • 19
  • 31