How can I create a script in Webflow to close modals with embedded videos when the .close-modal button is clicked?

TL;DR
  • Add custom code in Webflow's "Custom Code" tab to target modal closure.
  • Use JavaScript to link the .close-modal button, ensuring videos are paused or reset when the modal closes.
  • Test the implementation in a live environment to confirm functionality.

Creating a script to close modals with embedded videos in Webflow involves using custom code and ensuring that videos stop playing when the modal is closed.

1. Add Custom Code to Your Project

  • Access your Webflow dashboard and open the relevant project.
  • Go to the "Project Settings," then select the "Custom Code" tab.
  • Insert the script inside the <head> tag or the "Footer Code" section, depending on your preference.

2. Write the Script

  • Use JavaScript to link the .close-modal button to the modal's closing function.

  

<script>
// jQuery is typically available in Webflow; ensure jQuery is included in your project.
$(document).ready(function() {
  $('.close-modal').click(function() {
    // Hide the modal container
    $(this).closest('.modal-container').hide();

    // Find the video elements within the modal and pause them
    $(this).closest('.modal-container').find('video, iframe').each(function() {
      // For HTML5 video elements
      if ($(this).is('video')) {
        this.pause();
        this.currentTime = 0; // reset the video to the start
      }
      // For iframes (like YouTube or Vimeo videos)
      if ($(this).is('iframe')) {
        let src = $(this).attr('src');
        $(this).attr('src', ''); // temporarily remove the src
        $(this).attr('src', src); // reassign the src to reset the video
      }
    });
  });
});
</script>

3. Test the Implementation

  • Publish the site and test the modals on the live environment.
  • Ensure that the modal closes correctly and that all videos stop playing and/or reset when the *.close-modal button is clicked.

Summary

To close modals with embedded videos in Webflow, add custom JavaScript that targets the modal’s .close-modal button. This script should also reset or pause any embedded videos when the modal is closed. Always test the implementation in a live environment to ensure it functions as expected.

Rate this answer

Other Webflow Questions