Search code examples
javascriptkeydownkeyup

I'm trying to make a programme which flashes an image when the "a" key is pressed


<div class="planeta" id="planeta">
  <img src="planeta.jpg" style="width: 150px; height: 150px;">
  <div class="text-blocka">
    <h4>Kepler-186f</h4>
    <p>550 light years away</p>
  </div>
</div>

The first part of the code works and the image begins to flash, but i want it to cancel the flash when the key is released and this part is not working for me. Below is the javascript i have written so far. Thanks in advance!

function checkKeydowna(akey) {
    if (akey.keyCode == "65") {
      var img = document.getElementById('planeta');

var interval = window.setInterval(function(){
    if(img.style.visibility == 'hidden'){
        img.style.visibility = 'visible';
    } else {
      img.style.visibility == 'hidden'
      }
}, 50);
    }
}

window.addEventListener("keyup", checkKeyupa, false);

function checkKeyupa(abkey) {
    if (abkey.keyCode == "65") {
    delete window.setInterval();
    }
  }

Solution

    • You forgot addEventListener for checkKeydowna.
    • delete window.setInterval(); is meaningless. that doesn't clear interval. you should clear interval with window.clearInterval(intervalInstance). So if you want to clear an interval you should store that in a global varible when you set it. That is why I declare var interval = false; which also means interval didn't set.
    • Keydown event will be triggered multiple times, so you should check if interval is set or not to avoid reinitialize it.

    var interval = false;
    function checkKeydowna(akey) {
      if (akey.keyCode == "65") {
        var img = document.getElementById('planeta');
    
        if (!interval) {
          interval = window.setInterval(function() {
            if (img.style.visibility == 'hidden') {
              img.style.visibility = 'visible';
            } else {
              img.style.visibility = 'hidden'
            }
          }, 50);
        }
      }
    }
    
    document.body.addEventListener("keyup", checkKeyupa, false);
    document.body.addEventListener("keydown", checkKeydowna, false);
    
    function checkKeyupa(abkey) {
      if (abkey.keyCode == "65") {
        window.clearInterval(interval);
        interval = false;
        var img = document.getElementById('planeta');
        img.style.visibility = 'visible';
      }
    }
    <img style='visibility:visible' src="https://www.google.com.tr/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png" id="planeta" />