Skip to content
Advertisement

different vars and ifs for different videos not working

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!

Advertisement

Answer

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;
    }
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement