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
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>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.