I have a <video>
tag and want to listen on its keydown event. Below is the code:
html:
<div>
<video src=".mp4" controls onkeydown="key()">
</video>
</div>
javascript:
function key(e) {
console.log(e.keyCode)
}
when I play the video and type some key from keyboard, it doesn't fire the key
function. what is the correct way to listen on a video key event?
I also tried below code but it doesn't work:
document.querySelector("video").onkeydown = function(e) {
console.log(e.keyCode)
}
I have a <video>
tag and want to listen on its keydown event. Below is the code:
html:
<div>
<video src="https://www.w3schools./html/mov_bbb.mp4" controls onkeydown="key()">
</video>
</div>
javascript:
function key(e) {
console.log(e.keyCode)
}
when I play the video and type some key from keyboard, it doesn't fire the key
function. what is the correct way to listen on a video key event?
I also tried below code but it doesn't work:
document.querySelector("video").onkeydown = function(e) {
console.log(e.keyCode)
}
Share
Improve this question
edited Oct 21, 2018 at 3:03
Joey Yi Zhao
asked Oct 21, 2018 at 2:28
Joey Yi ZhaoJoey Yi Zhao
42.8k88 gold badges358 silver badges662 bronze badges
1
- Are you sure need a keydown event? I mean, Video element offers some methods and events for you to track down and do something on video. html5rocks./en/tutorials/video/basics – HalfWebDev Commented Oct 21, 2018 at 3:08
3 Answers
Reset to default 7To get a button press event called, you need to be focused on the element specified. Here, for some reason, you can't focus on the video automatically, so just hack it in when you play the video like this:
var video = document.getElementById('vid')
video.addEventListener('keydown', (e) => {
console.log(e);
});
video.addEventListener('play', () => {
video.focus();
});
jsfiddle: https://jsfiddle/238bygu7/
(Also make sure to add an id to your video in this case)
var video = document.getElementsByTagName('video')[0]
video.addEventListener('keypress', function (e) {
console.log(e)
})
video.addEventListener('playing', function (e) {
video.focus()
})
<video src="https://www.w3schools./html/mov_bbb.mp4" controls></video>
The key event is captured only when the DOM element is focus.
document.getElementsByTagName('video')[0].addEventListener('keydown', function(e){
if(e.key === 'Enter'){
//Your Code Here
}
});