Reputation: 435
i wanted to pause my video after clicking on the video.
While using the commands in the console everything works as it should. But if i use jQuery it does not work. Anyone know why?
$("#video").click(function() {
if(!$("#video").get(0).paused) {
console.log("playing");
showPlayBtn();
$("#video").get(0).pause();
} else {
console.log("paused");
}
});
Html:
<video id="video" preload="auto">
<source src="path/to/video.mp4" type="video/mp4">
Your browser does not support the Videoplayer
</video>
Upvotes: 1
Views: 3277
Reputation: 794
Since .pause()
is a native VideoElement's method and not jQuery's method, you need a reference to it. But using: $("#video").get(0)
to reference the video object inside handler function isn't necesarry, instead of that you can use just this which reference the same object.
You can check it:
$("#video").click(function() {
console.log($("#video").get(0)==this); //true
}
I've checked your code in 2 different browsers and it does work. But perhaps you tried to call $("#video"), before it's actually loaded. to fix that - add it after loading, for example like this:
$(function(){
//inside here -> means after loading. So video element already exist
$("#video").click(function() {
if(!this.paused) { //if this video element is NOT paused
console.log("playing");
showPlayBtn(); //some function of yours
this.pause(); //pause this video element
} else {
console.log("paused");
}
});
});
Upvotes: 1
Reputation: 2938
You've got a mistake in your code missing a selector inside the if
check:
$("#video").click(function() {
if(!$(this).get(0).paused) {
console.log("playing");
showPlayBtn();
$(this).get(0).pause();
} else {
console.log("paused");
}
});
Or to be somewhat more efficient:
$("#video").click(function() {
var video = $(this).get(0);
if(!video.paused) {
console.log("playing");
showPlayBtn();
video.pause();
} else {
console.log("paused");
}
});
Here are my jQuery play/pause wrappers for html5 - things are wrapped in try/catch for when it isn't supported:
/**
* Play an audio or video element
* @method play
* @for jQuery
* @chainable
* @return {jQuerySelector}
*/
$fn.play = function() {
return this.each(function() {
try {
this.play();
} catch (e) {
}
});
};
/**
* Pause an audio or video element
* @method pause
* @for jQuery
* @chainable
* @return {jQuerySelector}
*/
$fn.pause = function() {
return this.each(function() {
try {
this.pause();
} catch (e) {
}
});
};
Upvotes: 0