How can I stop a YouTube video from playing in a custom modal on Webflow when the modal is closed?

Published on
September 22, 2023

To stop a YouTube video from playing in a custom modal on your Webflow site when the modal is closed, you can use JavaScript in combination with the YouTube API. Here's how you can achieve this:

  1. Add the YouTube iframe API script to your site:
  1. Create a custom modal on your Webflow site:
  • Add a button or any element that triggers the modal.
  • Create a div as the modal container and style it according to your design.
  1. Embed the YouTube video inside the modal:
  • Drag and drop an embed element into the modal container div.
  • In the YouTube video URL, change "watch?v=" to "embed/" to get the embed URL. For example, change https://www.youtube.com/watch?v=VIDEO_ID to https://www.youtube.com/embed/VIDEO_ID.
  • Configure the embed element's settings (autoplay, controls, etc.) to fit your requirements.
  1. Add JavaScript to control the video playback:
  • In your Webflow designer, select the page where the custom modal is located.
  • Click on the </> symbol in the top-right corner to access the Custom Code panel.
  • In the Head Code section, paste the following JavaScript function:
    ```javascript ```
  • This function uses the YouTube API to stop the video playback when called.
  1. Add an event listener to the modal close button:
  • Select the close button element inside your modal.
  • In the Settings panel, go to the On Click event section and click + Add New Interaction.
  • Choose the Run JavaScript action and enter stopVideo(); as the function to execute.
  1. Publish your site and test:
  • Preview or publish your Webflow site.
  • Open the modal by triggering it and play the video.
  • Close the modal and ensure that the video stops playing.

By following these steps, you can ensure that YouTube videos embedded in your custom modals on Webflow will stop playing when the modal is closed, providing a better user experience.

Additional questions:

  1. How do I embed a YouTube video in Webflow?
  2. Can I customize the appearance of the YouTube player in Webflow?
  3. What other methods can be used to embed videos on Webflow?