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

TL;DR

To create a script in Webflow that closes modals with embedded videos when the `.close-modal` button is clicked, you can follow these steps:

​

1. Add a custom code block to your Webflow project. You can do this by going to the Designer and dragging a "Custom Code" element onto your page or by going to the Project Settings and adding the code to the "Custom Code" section.

​

2. Place the following script inside the custom code block:

​

```javascript

<script>

  // Wait for the DOM to fully load

  document.addEventListener('DOMContentLoaded', function() {

    // Get all elements with the class name "close-modal"

    var closeModalButtons = document.querySelectorAll('.close-modal');

​

    // Loop through each button

    for (var i = 0; i < closeModalButtons.length; i++) {

      // Add a click event listener to each button

      closeModalButtons[i].addEventListener('click', function() {

        // Get the modal element associated with the clicked button

        var modal = this.closest('.modal');

​

        // Check if the modal contains an embedded video

        var video = modal.querySelector('iframe[src*="youtube"], iframe[src*="vimeo"]');

​

        // Pause the video if it exists

        if (video) {

          var videoSrc = video.src;

          video.src = videoSrc;

        }

​

        // Hide the modal by removing the "show" class

        modal.classList.remove('show');

​

        // Prevent the default button click behavior

        event.preventDefault();

      });

    }

  });

</script>

```

​

3. Make sure to replace `.close-modal` with the correct class or selector of your close button, and `.modal` with the class or selector of your modal element.

​

4. Save your changes and publish your Webflow site.

​

Now, when the `.close-modal` button is clicked, the script will find the nearest modal element, pause any embedded video inside it (if applicable), and remove the `show` class from the modal to hide it. This script should work for modals that contain embedded videos from YouTube or Vimeo. If you're using a different video platform, you may need to adjust the `querySelector` condition.

​

Remember to apply the `.close-modal` class to your close button and add the `.modal` class to your modal element for the script to work correctly.

Rate this answer

Other Webflow Questions