Reputation: 1641
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();
});
});
Upvotes: 0
Views: 59
Reputation: 1641
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();
});
});
Upvotes: 0
Reputation: 28513
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();
});
Upvotes: 1