Multiple modals on a page using Data Attributes

<!-- Modal --> <div class="modal" data-modal="video"> <div class="video-container"> <iframe width="560" height="315" src="https://www.youtube.com/embed/fUOVQ4KsX9U" frameborder="0" allowfullscreen></iframe> </div> <!-- Close modal --> <a href="#" data-modal-close="video">Close</a> </div> <!-- Open modal --> <a href="#" data-modal-open="video">Open</a> <script> // Data attr modal // Global video variables var vid = $('.video-container iframe[src*="youtube"]'), src = vid.attr('src'); // Open $('[data-modal-open]').on('click', function(e){ // Grab value from the attr var targeted_modal_class = $(this).attr('data-modal-open'); vid.attr('src', src); // Populate youtube src $('[data-modal="' + targeted_modal_class + '"]').addClass('is-visible'); e.preventDefault(); }); // Close $('[data-modal-close]').on('click', function(e){ var targeted_modal_class = $(this).attr('data-modal-close'); vid.attr('src', ''); // Clear youtube src $('[data-modal="' + targeted_modal_class + '"]').removeClass('is-visible'); e.preventDefault(); }); </script>
In this snippet I have loaded a Youtube video embed in the modal window. In the script, the open and close functions store and clears the embed src, so when you close the modal, it stops the video from playing, and when you open the modal back up, it restores the src.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.