I am trying to bind play
/pause
and ended
events using jQuery but there is a problem:
When I right click on the video and select play or pause the icons change correctly. When I click the play button it changes to pause, but if I click the pause button to continue the video it doesn't change to play again.
Can anyone tell me where I am going wrong?
Here is my code:
var PlayVideo = function () {
if ($('#video').attr('paused') == false) {
$('#video').get(0).pause();
} else {
$('#video').get(0).play();
}
};
$('#playbtn').click(PlayVideo);
$('#video').click(PlayVideo);
$('#video').bind('play', function () {
$('.playbtn').addClass('pausebtn');
});
$('#video').bind('pause', function () {
$('.playbtn').removeClass('pausebtn');
});
$('#video').bind('ended', function () {
$('.playbtn').removeClass('pausebtn');
});
CSS:
.playbtn {
display: block;
width: 32px;
height: 32px;
margin-left: 10px;
background: url('../images/play.png') no-repeat;
opacity: 0.7;
-moz-transition: all 0.2s ease-in-out; /* Firefox */
-webkit-transition: all 0.2s ease-in-out; /* Safari and Chrome */
-o-transition: all 0.2s ease-in-out; /* Opera */
transition: all 0.2s ease-in-out;
}
.pausebtn {
display: block;
width: 32px;
height: 32px;
margin-left: 10px;
background: url('../images/pause.png') no-repeat;
opacity: 0.7;
-moz-transition: all 0.2s ease-in-out; /* Firefox */
-webkit-transition: all 0.2s ease-in-out; /* Safari and Chrome */
-o-transition: all 0.2s ease-in-out; /* Opera */
transition: all 0.2s ease-in-out;
}
There is no
pause
-attribute for HTML5 video. Instead you should have a look at media events and properties.In your case that would mean:
BTW: Since you are calling
$('#video')
pretty often it might be a good idea to store that in a variable - this way you don't have to call the jQuery-selector a gazillion times. Like:EDIT: Regarding your comment it is hard to tell without seeing the controls (HTML & CSS) you are using but what you can do in any case is using the same handler for all the events that trigger the same behavior (and since the behavior is right on
pause
it should be onended
as well when bound to the same handler). Also, in the code you posted, you are usingremoveClass
on ended (where it should probably beaddClass
). So this should work:Another glitch i noticed is that you use
#playbtn
once and.playbtn
another time. Make sure you are referring to the same items here when trying to do something with your Play-Button.