Playing and pausing videos | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Playing and pausing videos

How to play and pause videos with JavaScript (not HTML!)? I want to autoplay a video when a certain button is pressed, so I need to start playing the video with JavaScript. I know putting ?autoplay=1 after the link in HTML will help, but that won't help me, because it'll autoplay the video when the code has loaded, not when the button is clicked. W3schools offered that video.play(); would help, but I'm getting 'video.play is not a function' (yes I defined video with the Id from HTML first) https://www.w3schools.com/tags/av_met_play.asp Also (might be) important: it's a YouTube video, so a YouTube link. Could anyone help me out?

27th Jun 2017, 9:07 PM
Maart
Maart - avatar
3 Answers
+ 2
I tried some things out, kept having trouble with it, but eventually this fixed it: document.getElementById("video").src += "?autoplay=1"; Makes sense after all
28th Jun 2017, 9:04 AM
Maart
Maart - avatar
+ 1
First, make sure you're using getElementById and not getElementsByTagName. If that doesn't work try using this jquery script and replace .video with the defined class or ID $('.video').click(function(){this.paused?this.play():this.pause();}); Also ensure that you're using a <video> element, YouTube videos won't work for these, and if you want to use something other than YouTube's player, I suggest using a video file using a supported format
27th Jun 2017, 9:28 PM
Jared
Jared - avatar
0
I am using getElementById, yeah. I'll try out the jQuery option later!
27th Jun 2017, 9:47 PM
Maart
Maart - avatar