Reputation: 19
I'm trying to create the function that if a key is pressed, a video appears. I have managed to do it for one key and it works fine:
var video = document.getElementById('b1');
document.addEventListener('keydown', (e) => {
if(e.key === "b") {
video.play(); video.currentTime = 0;
}
});
But i want to do this for several different keys, (26 to be exact). I figured that what I needed to do was copy the same code and place it below, like this:
var video = document.getElementById('b1');
document.addEventListener('keydown', (e) => {
if(e.key === "b") {
video.play(); video.currentTime = 0;
}
});
var video = document.getElementById('d1');
document.addEventListener('keydown', (e) => {
if(e.key === "d") {
video.play(); video.currentTime = 0;
}
});
But i get the error: "'video' is already defined. Do not redeclare". I get that what's wrong is the composition of the code but I spent a while looking for the right way to do it and couldn't find it. Any help would be really appreciated!
Upvotes: 0
Views: 41
Reputation: 1075
In fact if you write
var video = document.getElementById('b1');
document.addEventListener('keydown', (e) => {
if(e.key === "b") {
video.play(); video.currentTime = 0;
}
});
var video = document.getElementById('d1');
document.addEventListener('keydown', (e) => {
if(e.key === "d") {
video.play(); video.currentTime = 0;
}
});
you are trying to define the variable video more than once, which is not allowed. If you have multiple elements with different ids you should add different variable names.
Even better, you could do like:
setListener(elementID, keyToHaveEffect) {
const videoElement = document.getElementById(elementID);
if (e.key === keyToHaveEffect) {
if (videoElement) {
videoElement.play(); videoElement.currentTime = 0;
}
}
}
and then call it like
setListener('b1' , 'b')
Upvotes: 1
Reputation: 782735
A variable can only have one value. When you reassign video
, the old value is lost. When the event listeners fire, they'll use the last value that was assigned, so both keys will play the same video.
You can use different variables, or better would be to use an object that maps keys to videos.
var videos = {
'b': document.getElementById('b1'),
'd': document.getElementById('d1')
}
document.addEventListener('keydown', e => {
let video = videos[e.key];
if (video) {
video.play();
video.currentTime = 0;
}
});
Upvotes: 2