Twice keypress different function running

l have 2 functions, l want to do like when the first keydown run one function than if its another keydown run the second function!

It is play/pause video function by spaceBar!

document.addEventListener('keydown', function(e) {
  if (e.keyCode == 32) {
    pauseAllVideos();
  } else {
    playAllVideos();
  }
});

Upvotes: 0

Views: 36

Answers (1)

Harry Punia
Harry Punia

Reputation: 61

Solution

Its all about saving a boolean value that lets you know if all videos are playing or not and then use it in the if statements.

Here is the code snippet:

let playing = false;

        const playAllVideos = () => console.log('playing all videos');

        const pauseAllVideos = () => console.log('paused all videos');

        const playPause = e => {
          let key = e.keyCode || e.which;//Get key
          if(key == 32) { //Space key
            if(playing) {//If playing turn all videos off
              pauseAllVideos();
              playing = false;
            } else {//vise versa
              playAllVideos();
              playing = true;
            }
          }
        }

        window.addEventListener('keypress', playPause);
<p>Press Space</p>

Upvotes: 1

Related Questions