Reputation: 847
I have a jQuery click function set up to play/pause an HTML5 video, and I'm wondering how I might go about also showing/hiding the controls. Thus, I would like to initially hide the controls-- i.e. when the poster graphic is showing-- and then show them when the video is clicked to play (and also to hide them again when the video is clicked to pause.)
I have a fiddle set up here.
Thanks much for any assistance.
$("video#click").click(function(){
this.paused?this.play():this.pause();
return false;
});
#click {
max-width: 500px;
height: auto;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<video preload="auto" id="click">
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type='video/mp4;codecs="avc1.42E01E, mp4a.40.2"' />
</video>
Upvotes: 1
Views: 16648
Reputation: 7853
This is a little trickier than it might seem it should be, because of the way the built-in media controls behave. The first challenge is that you don't have any way to know whether the user is actively interacting with the controls. So if you hide the controls any time the user clicks, then you'll hide them while they're seeking or adjusting the volume. So I suggest you don't have the video pause on click, but you can still have it play on click.
The second challenge is that the video is paused and fires the 'pause' event whenever the user seeks with the controls. So you have to only remove the controls when the mouse button is not down. Here's what it could look like.
var $video = $("#click"), //jquery-wrapped video element
mousedown = false;
$video.click(function(){
if (this.paused) {
this.play();
return false;
}
return true;
});
$video.on('mousedown', function () {
mousedown = true;
});
$(window).on('mouseup', function () {
mousedown = false;
});
$video.on('play', function () {
$video.attr('controls', '');
});
$video.on('pause', function () {
if (!mousedown) {
$video.removeAttr('controls');
}
});
You may also want to do the same thing for touch events, and you may want to filter to make sure it's just the left mouse button. I'll leave that up to you.
Here's a link to a working example: http://jsbin.com/soyate/1/edit
Upvotes: 4