user3702848
user3702848

Reputation: 155

Html5 Video - Play/Pause video on screen click

,Hi,

    <!DOCTYPE html> 
<html> 
<body> 

<div style="text-align:center"> 
  <button onclick="playPause()">Play/Pause</button> 
  <button onclick="makeBig()">Big</button>
  <button onclick="makeSmall()">Small</button>
  <button onclick="makeNormal()">Normal</button>
  <br> 
  <video id="video1" width="420">
    <source src="mov_bbb.mp4" type="video/mp4">
    <source src="mov_bbb.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
  </video>
</div> 

<script> 
var myVideo=document.getElementById("video1"); 

function playPause()
{ 
if (myVideo.paused) 
  myVideo.play(); 
else 
  myVideo.pause(); 
} 

function makeBig()
{ 
myVideo.width=560; 
} 

function makeSmall()
{ 
myVideo.width=320; 
} 

function makeNormal()
{ 
myVideo.width=420; 
} 
</script> 

<p>Video courtesy of <a href="http://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.</p>
</body> 
</html>

I try to use html5 video from below website

http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_video_js_prop

How can i play/pause video on video screen click ?

Any help will be appreciated.

Thanks.

Upvotes: 5

Views: 34816

Answers (2)

jave.web
jave.web

Reputation: 15072

The shortest way

onclick="this[this.paused ? 'play' : 'pause']()"

The right (but still short) way

...considering you already have your video in variable,
you should generally use event listeners and not hard coded onX attributes...
(even if you have callback!)

var myVideo = document.getElementById("video1");
myVideo.addEventListener('click', function(e){
   e.preventDefault();
   this[this.paused ? 'play' : 'pause']();
});

PS: If you are wondering how the hack does the play/pause line work - it is based on the fact that in JavaScript, methods/object functions are basically callable properties of that object and also that in JavaScript, you can reference property directly someObj.someProperty but also through value or variable like someObj["someProperty"] , var prop = "someProperty"; someObj[prop];

... so a long equivalent of the one-liner would be

if (this.paused) {
   this.play();
} else {
   this.pause();
}

Upvotes: 2

shabeer
shabeer

Reputation: 1064

Simply you can call the function video on click

<video id="video1" onClick="playPause();">
...
</video>

Upvotes: 6

Related Questions