Creating a dynamic lightbox for YouTube and Vimeo videos in Webflow requires some setup to ensure that the video playback stops when the modal is closed.
1. Add Lightbox Link to Collection List
- Open your Webflow project.
- Drag a Collection List into your page from the Add Panel.
- Bind the Collection List to your desired collection by selecting “Get Items From” and choosing your collection.
2. Embed a YouTube/Vimeo Video
- Place a Video Embed element inside the Collection Item.
- In the Embed settings, use the embed code from YouTube/Vimeo, replacing the video URL dynamically with the CMS field. Use the format:
https://www.youtube.com/embed/{{Video URL}} or for Vimeo, https://player.vimeo.com/video/{{Video ID}}.
3. Add a Lightbox Trigger
- Drag in a Button or Link Block inside the Collection Item.
- Select the Button/Link Block as the trigger for the lightbox.
4. Create a Modal Lightbox
- Create a new Div Block for the modal overlay somewhere in your project.
- Ensure this Div Block is set to fixed position and covers the full viewport.
- Inside this Div, place the Video Embed element again for the video to play.
5. Add Close Functionality to Modal
- Add a Close Button inside the modal.
- Set Interactions on this button to close the modal and stop the video.
6. Use Custom Code to Stop Video on Modal Close
- You will need to use some custom JavaScript to stop the video playback.
- Go to Project Settings and add the following script in the Custom Code section (Before Body Tag):
document.addEventListener('DOMContentLoaded', function() {
const modal = document.querySelector('.your-modal-class');
const iframe = modal.querySelector('iframe');
modal.addEventListener('click', function() {
// Stop playing the video
const src = iframe.src;
iframe.src = ''; // Empty the src attribute
iframe.src = src; // Set it back to restart the video
modal.style.display = 'none'; // Hide the modal
});
});
7. Publish and Test
- Publish your site and open it in a browser.
- Test the lightbox functionality to ensure it opens and the video stops playing once closed.
Summary
To create a dynamic lightbox for YouTube and Vimeo videos on Webflow, set up a modal with a video embed linked to your CMS collection, and apply custom JavaScript to ensure videos stop when the lightbox is closed. This solution combines Webflow's Collection capabilities with HTML/CSS for structure and JavaScript for functionality.