How to play and pause autoplay video depending on layout status

I have a interaction where when users click on an icon it changes the video embed from none (hidden) to Flex and vice versa. Ive set it to autoplay and works beautifully but when I close it the video is still playing in the background and i can hear the audio.

How do I add a script to each of the Embed so that the video plays and pauses depending on its Layout status or visibility?

I have no coding knowledge but I followed a youtube video and copied its code and it works on one of the embed! (it even pauses when i scroll away which is a function that i didnt need but is cool hehe), but I have 3 of these video popups and when i copy and paste this code to the others they dont work. So I need a new solution or a way to make this solution work with the other embeds.

this is the code

Your browser does not support the video tag.

*Im hosting the videos from AWS

---------- Here is my site Read-Only: **[LINK][1]** ([how to share your site Read-Only link][2])

oh sorry that just put a video in the post sorry
heres the code that works


<video id='myVideo' width="100%" height="100%" loop autoplay>
  <source src="https://duskwebflow.s3.ap-southeast-1.amazonaws.com/Pillar+1+42v73+Vid.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

<script>
let options = {
root: null,
rootMargin:'0px',
threshold:1.0
};
let callback = (entries, observer)=>{
entries.forEach(entry => {
if(entry.target.id == 'myVideo')
{
if(entry.isIntersecting){
entry.target.play();
}
else{
entry.target.pause();
}
}
});
}
let observer = new IntersectionObserver(callback, options);
observer.observe(document.querySelector('#myVideo'));
</script>

Search Youtube for PixelGeeks video on auto-playing (and stoping the playback) of videos on scroll. Not exactly what you’re looking for but will give you the pieces to make yours work.

Sorry, I couldn’t quickly find the link otherwise I’d post it here :expressionless: