SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Activating when key is held down

    I'd like to run a function when a key is held down on the webpage for a number of seconds. A "hold X for 3 seconds to activate" type of thing without any inputs -- just code attached to the window.

    I've been messing around for an hour adding keydown/keyup events and timers to try to get this to work. It seems tricky since some browsers call keydown each time the character you're holding autorepeats from being held, some don't, some keep calling keypress as well... so I try to build in a timer that doesn't reset unless the time since the last event fire is a certain amount of time...

    Anyway, it's messy and I don't have it working right.

    Anyone have some pointers or useful sites for making this happen reliably in all browsers?

  2. #2
    SitePoint Evangelist
    Join Date
    Mar 2006
    Location
    Sweden
    Posts
    451
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Something like this perhaps?

    Code:
    window.onload = function()
    {
    	document.onkeydown = keyDown;
    	document.onkeyup = keyUp;
    }
    
    var keytimer = false;
    function keyDown()
    {
    	if( !keytimer ) keytimer = setTimeout( keyPressed3Sec, 3000 );
    }
    
    function keyPressed3Sec()
    {
    	alert( 'yeay!' );
    	clearIt();
    }
    
    function keyUp()
    {
    	if( keytimer ) clearIt();
    }
    
    function clearIt()
    {
    	clearTimeout( keytimer );
    	keytimer = false;
    }

  3. #3
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Works great, thanks


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •