I have this code that allows me to stop YouTube videos from playing once a button is pressed. Here is an example:
//Hotel Post
<script>
$(document).ready(function() {
// set unique id to videoplayer for the Webflow video element
var src = $('#videoplayer').children('iframe').attr('src');
// when object with class open-popup is clicked...
$('.open-popup.left').click(function(e) {
e.preventDefault();
// change the src value of the video
$('#videoplayer').children('iframe').attr('src', src);
$('.popup-bg').fadeIn();
});
// when object with class close-popup is clicked...
$('.close-modal-button').click(function(e) {
e.preventDefault();
$('#videoplayer').children('iframe').attr('src', '');
$('.popup-bg').fadeOut();
});
});
</script>
//Gans to go
<script>
$(document).ready(function() {
// set unique id to videoplayer for the Webflow video element
var src = $('#videoplayer2').children('iframe').attr('src');
// when object with class open-popup is clicked...
$('.open-popup.left').click(function(e) {
e.preventDefault();
// change the src value of the video
$('#videoplayer2').children('iframe').attr('src', src);
$('.popup-bg').fadeIn();
});
// when object with class close-popup is clicked...
$('.close-modal-button').click(function(e) {
e.preventDefault();
$('#videoplayer2').children('iframe').attr('src', '');
$('.popup-bg').fadeOut();
});
});
</script>
I have about 14 videos like this embedded on my site and it makes things slow, because I have one of these scripts for every video. Is there any way I can select several ids at once or something? So I have one script for all videos?
I would appreciate the help. Thanks a lot. Pablo
One way is to set all the videos to have a common className, like video and store the variable src into a data-attribute.
$(document).ready(function() {
// set unique id to videoplayer for the Webflow video element
$('.video').each(function() {
let src = $(this).children('iframe').attr('src');
$(this).attr('data-src', src);
})
// when object with class open-popup is clicked...
$('.open-popup.left').click(function(e) {
e.preventDefault();
// change the src value of the video
$('.video').each(function() {
$(this).children('iframe').attr('src', $(this).data('src'));
$('.popup-bg').fadeIn();
});
// when object with class close-popup is clicked...
$('.close-modal-button').click(function(e) {
e.preventDefault();
$('.video').each(function() {
$(this).children('iframe').attr('src', '');
$('.popup-bg').fadeOut();
});
});