Jump to content

how to detect if a key is being held


optikalefx

Recommended Posts

so im using this kind of listener  document.addEventListener('mousedown',function,true);

this is only for firefox.

 

how can i make var num increase as you hold down the arrow key

 

i already can detect if the arrow is pressed, but not held. its called once, and it should keep on calling it.

 

//for down arrow

if (e.keyCode == "40") {

 

}

Link to comment
https://forums.phpfreaks.com/topic/96656-how-to-detect-if-a-key-is-being-held/
Share on other sites

This uses a slgihtly different method, but works in FF and IE and gives you the time the mouse was down. Change 'interval' to the unit of time that you need to capture (100 = 10ths of a second):

<HTML>
<HEAD>
<script type="text/javascript">

var interval = 100; //milliseconds

var mdown = false;
var seconds = 1000/interval;

function init() {
    document.onmousedown = function (e) {
        mdown = true;
        changeState(mdown);
        startTimer(0);
    }

    document.onmouseup = function (e) {
        mdown = false;
        changeState(mdown);
    }
}

function changeState(state) {
  document.getElementById('mdstate').innerHTML = state;
}

function startTimer(timeDown) {
  if (mdown) {
    document.getElementById('mdtime').innerHTML = Math.round(timeDown/1000*seconds)/seconds;
    setTimeout('startTimer('+(timeDown+interval)+')', interval);
  }
}


</script>


</HEAD>

<BODY onload="init();">
  Mouse Down State: <span id="mdstate"></span><br>
  Mouse Down Time: <span id="mdtime"></span>
</BODY>
</HTML>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.