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 Project Settings under the Custom Code section, either for a specific page or all pages.
  • Implement a script that attaches a click event to .close-modal buttons, pauses videos, and hides modals.
  • Publish and test the functionality by making sure clicking .close-modal stops the video and closes the modal correctly.

Creating a script in Webflow to close modals with embedded videos when the .close-modal button is clicked involves using custom code within the Webflow Designer.

1. Add Custom Code in Webflow

  • Go to Project Settings in your Webflow dashboard.
  • Navigate to the Custom Code section.
  • Ensure you have a space to enter code in the Body tag area for the specific page or in the Page Settings for all.

2. Implement the Script

  • Enter the custom script that listens for a click on the .close-modal button and stops video playback.
  • Use inline references as necessary.

Sample steps:

  • Query the document to find all the modals and attach a click event to the modal buttons.
  • Identify the video element embedded in the modals, and use HTML5 methods to pause the video or stop auto-play (attributes like loading="lazy" may be useful).

3. Script Example

  • Here's how a generic action might look:

document.querySelectorAll('.close-modal').forEach(button => {
  button.addEventListener('click', function() {
    const modal = this.closest('.modal');
    const video = modal.querySelector('video');
    if (video) {
      video.pause();
      video.currentTime = 0;
    }
    modal.style.display = 'none'; // or apply a class to hide
  });
});

4. Publish and Test

  • Publish your Webflow project to see changes in action.
  • Test clicking the .close-modal button to ensure the video stops and the modal closes correctly.

Summary

To close modals with embedded videos when the .close-modal button is clicked in Webflow, you must use a custom script that pauses the video and hides the modal on click. Add this script to your project’s custom code section, ensuring it identifies video elements and attaches the necessary event listeners accurately.

Rate this answer

Other Webflow Questions