'Use jQuery code to play a YouTube video on click on custom button more than once on a page?
I am developing a WordPress Theme with ACF and blocks. One of the blocks has a YouTube video embedded that opens as a module/popup and should automatically start playing when the user clicks to open the module/popup. Also when the user clicks the close button of the module/popup, the video should stop playing.
I found a code that works but only for one instance per page as it depends on the right classes. When my client would add a 2nd instance of that block, and the user opens this module/popup, the other (first) video actually start playing in the background.
Can anyone help me to rewrite the code to be able to use it multiple times on a page?
Here is my HTML:
<div data-w-id="d0f29131-3fc1-c17d-1d06-cac855c814b2" class="behandlung_details_rechts" style="background-image:url('<?php echo get_field( 'bild_video_bild' ); ?>');">
<a data-w-id="c77b6487-4cbc-7de8-8415-fa31986a0544" href="#" class="behandlung_details_overlay play-video w-inline-block">
<div style="background-image: url(<?php echo get_theme_file_uri('images/play.png') ?>); -webkit-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);-moz-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);-ms-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0)" class="play_button"></div>
</a>
</div>
<div style="display:none;opacity:0" class="video_popup_wrapper">
<div class="video_div">
<div class="html-embed w-embed w-iframe"><iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube-nocookie.com/embed/<?php the_field('bild_video_video_id'); ?>?enablejsapi=1" modestbranding="0" controls="0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
</iframe></div>
</div>
<a data-w-id="ccf28eaf-2e0e-5002-536f-6d47e7efb6d7" href="#" style="background-image: url(<?php echo get_theme_file_uri('images/close.png') ?>);" class="stop-video w-inline-block"></a>
</div>
And
my Jquery:
$('a.play-video').click(function(){
$('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'playVideo' + '","args":""}', '*');
});
$('a.stop-video').click(function(){
$('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
