Reputation: 93
Javascript onclick on a HTML video element is not working.
EDIT: In Firefox (66.0.5 (64-Bit)) dont work. In Chrome (74.0.3729.131) works.
No errors in the console.
I will put a text in a div box when the video is clicking/started (with video lenght to wait).
function myfunction () {
console.log("onclick");
document.getElementById("videotextbox").innerHTML = "VIDEO-INFO";
}
<div>
<video onclick="myfunction()" id="videoid" width="600" controls>
<source src="myvideo.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
</div>
<div id="videotextbox"></div>
w3schools write:
Supported HTML tags: All HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>
Please a solution without jquery or ajax.
Upvotes: 4
Views: 1912
Reputation: 137141
This is because of the controls
. No browser does expose when users click on the controls of MediaElements.
You can try to click on the play button or the timeline from Chrome and you'll see that the click events are actually stopped.
In Firefox, these controls are covering the whole video element, and thus, you don't have any click event getting out on your element. (Technically, Chrome's too, and I suspect this is a bug they left when they made their updated player).
So if you really need the click events, then don't set the controls
attribute:
document.querySelector('video').onclick = e =>
console.log('clicked');
<video src="https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm" autoplay></video>
But generally, you don't need to listen for click events, but rather for Media events such as playing
, pause
, seek
etc.
const vid = document.querySelector('video');
['playing', 'pause', 'seeked', 'ended'].forEach(t =>
vid.addEventListener(t, e => console.log(t))
);
video{
max-height: 100vh;
margin-bottom: 100px;
}
<video src="https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm" controls></video>
Upvotes: 7
Reputation: 93
Alternative solution:
use HTML Audio/Video DOM ended Event.
var myvideo = document.getElementById("videoid");
myvideo.onended = function() {
document.getElementById("videotextbox").innerHTML = "VIDEO-INFO";
};
https://www.w3schools.com/tags/av_event_ended.asp
Upvotes: 0