Reputation: 458
I have a div that inside of it has a <video autoplay> <source src='myvid'> </video>
and by default the div has a display ='none'
on css. I am adding an event listener of click on the div and once its clicked i am changing the display none to display block.
the problem is that the video plays automatically when the site reloads and not when the button is clicked. basically i want the video to play only when the div is display ='block'. How can i do that in Javascript?
Upvotes: 2
Views: 7451
Reputation: 206689
autoplay
attribute<video id="video"> <source src='myvid'></video>
<button id="play">PLAY</button>
document.querySelector("#play").addEventListener("click", () => {
document.querySelector("#video").play();
});
If you don't want a custom button (not clear from your question) than you could provide the browser default by using the controls
attribute
const EL_video = document.querySelector("#video");
const EL_play = document.querySelector("#play");
EL_play.addEventListener("click", () => {
const isPaused = EL_video.paused;
EL_video[isPaused ? "play" : "pause"]();
EL_video.classList.toggle("u-none", !isPaused);
});
#video {width: 300px;}
/* Utility classes: */
.u-none {display: none;}
<button id="play">Toggle & play</button><br>
<video id="video" class="u-none">
<source src='http://vjs.zencdn.net/v/oceans.mp4' type='video/mp4'>
</video>
Upvotes: 4
Reputation: 149
try addind an onclick
attribute to the div like this:
<div onclick="play_video();">
Or you can create a button:
<button onclick="play_video();">play the video</button>
Then, create the javascript function like this:
function play_video()
{
document.getElementById("id_of_the_video").play();
}
Upvotes: 0