Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make same button play/pause html5 video

So i had this working at one point eventually i broke it and now i need to get it working again.

I want for when you press the PLAY button the video will start playing. and the PLAY button will change it text to say PAUSE. Then when you click it again the video will pause.

HTML:

<video id="myVideo" width="1024" height="576">
  <source src="myaddiction.mp4" type="video/mp4">
  <source src="myaddiction.mp4.ogg" type="video/ogg"> 
  Your browser does not support HTML5 video.
</video>

<button id="button" onclick="playPause(); ">PLAY</button>

SCRIPT:

var vid = document.getElementById("myVideo");

function playPause() {
  vid.play();
}

function playPause() {
  vid.pause();
}




function playPause() {
  var change = document.getElementById("button");
  if (change.innerHTML == "PLAY") {
    change.innerHTML = "PAUSE";
  } else {
    change.innerHTML = "PLAY";
  }
}

Here is also a fiddle with everything in it. If you know how to get a video working in it that'd be cool if you'd add it. Thanks!

https://jsfiddle.net/wb83hydn/

**EDIT: currently the problem is the video wont play when the button is pressed. The button changes text but the video does nothing.

like image 504
Warren Breedlove Avatar asked Jul 27 '26 08:07

Warren Breedlove


2 Answers

You are defining your playPause function 3 separate times. You are likely to get some unexpected results. That is, if the interpreter doesn't error out completely. You will be better served with just creating one function, and use a global variable to handle the tracking of the play/pause state. Something like this:

var vid = document.getElementById("myVideo");
var isPlaying = false;

function playPause() {
  var change = document.getElementById("button");
  if (isPlaying) {
    vid.pause();
    change.innerHTML = "PLAY";
  } else {
    vid.play();
    change.innerHTML = "PAUSE";
  }
  isPlaying = !isPlaying;
}
like image 141
Matt Spinks Avatar answered Jul 28 '26 20:07

Matt Spinks


Change your javascript to this to make it work. You'll need to make sure the DOM is loaded first by using window.onLoad or putting the JS at the end of the HTML file.

I updated the JSFiddle, but you'll need a valid online video file to make it work.

var vid = document.getElementById("myVideo");

function play() {
  vid.play();
}

function pause() {
  vid.pause();
}

function playPause() {
  var change = document.getElementById("button");
  if (change.innerHTML == "PLAY") {
    change.innerHTML = "PAUSE";
    play();
  } else {
    change.innerHTML = "PLAY";
    pause();
  }
}

https://jsfiddle.net/wb83hydn/3/

like image 39
earl3s Avatar answered Jul 28 '26 21:07

earl3s