Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6622673
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T21:26:15+00:00 2026-05-25T21:26:15+00:00

I’m trying to let a user move an element on the page using the

  • 0

I’m trying to let a user move an element on the page using the arrow keys. So far, I have movement working for up/down/left/right, but not for diagonal (two arrow keys pressed simultaneously).

My listener looks like this:

addEventListener('keydown', function(e){
    move = false;
    x = false;
    y = false;
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    switch(keycode){
        case 37:
            move = true;
            x = 'negative';
            //prevent page scroll
            e.preventDefault()
        break;
        case 38:
            move = true;
            y = 'negative'
            //prevent page scroll
            e.preventDefault()
        break;
        case 39:
            move = true;
            x = 'positive'
            //prevent page scroll
            e.preventDefault()
        break;
        case 40:
            move = true;
            y = 'positive'
            //prevent page scroll
            e.preventDefault()
        break;
    }
    if(move){
        animation.move(x,y);
    }
    return false;
})

The idea was that if the user presses an arrow key, it sets x and y to either negative or positive, and fires off the move() function, which will move the element a preset number of pixels in the desired direction, and that if two keys were pressed, a second event would fire… I also hope to be able to have the user seemlessly change directions by releasing and pressing keys rapidly Neither of these are happening, however, if the user presses another direction key, they seem to need to wait a momment for movement to happen, unless they completely release the key and then press another one, and it won’t respond to the second key at all until the first is released.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T21:26:15+00:00Added an answer on May 25, 2026 at 9:26 pm

    Fiddle: http://jsfiddle.net/ATUEx/

    Create a temporary cache to remember your key strokes.

    An implementation of handling two keys would follow this pattern:

    1. <keydown>
      • Clear previous time-out.
      • Check whether the a key code has been cached or not.
        If yes, and valid combination:
        - Delete all cached key codes
        - Execute function for this combination
        else
        - Delete all cached key codes
        - Store the new key code
        - Set a time out to clear the keycodes (see below), with a reasonable delay
    2. Repeat 1

    A reasonable delay: Experiment to know which timeout is sufficient for you. When the delay is too short, the next initiated event will not find a previously entered key code.

    When the delay is too long, the key strokes will stack when you don’t want it.


    Code

    I have created an efficient function, keeping your code in mind. You should be able to implement it very easily.

    (function(){ //Anonymous function, no leaks
        /* Change the next variable if necessary */
        var timeout = 200; /* Timeout in milliseconds*/
    
        var lastKeyCode = -1;
        var timer = null;
        function keyCheck(ev){
            var keyCode = typeof ev.which != "undefined" ? ev.which : event.keyCode;
            /* An alternative way to check keyCodes:
             * if(keyCode >= 37 && keyCode <= 40) ..*/
             /*37=Left  38=Up  39=Right  40=Down */
            if([37, 38, 39, 40].indexOf(keyCode) != -1){
    
                /* lastKeyCode == -1 = no saved key
                   Difference betwene keyCodes == opposite keys = no possible combi*/
                if(lastKeyCode == -1 || Math.abs(lastKeyCode - keyCode) == 2){
                    refresh();
                    lastKeyCode = keyCode;
                } else if(lastKeyCode == keyCode){
                    clear([lastKeyCode]);
                } else {
                    /* lastKeyCode != -1 && keyCode != lastKeyCode
                       and no opposite key = possible combi*/
                    clear([lastKeyCode, keyCode]);
                    lastKeyCode = -1
                }
                ev.preventDefault(); //Stop default behaviour
                ev.stopPropagation(); //Other event listeners won't get the event
            }
    
            /* Functions used above, grouped together for code readability */
            function reset(){
                keyCombi([lastKeyCode]);
                lastKeyCode = -1;
            }
            function clear(array_keys){
                clearTimeout(timer);
                keyCombi(array_keys);
            }
            function refresh(){
                clearTimeout(timer);
                timer = setTimeout(reset, timeout);
            }
        }
    
        var lastX = false;
        var lastY = false;
        function keyCombi(/*Array*/ keys){
            /* Are the following keyCodes in array "keys"?*/
            var left = keys.indexOf(37) != -1;
            var up = keys.indexOf(38) != -1;
            var right = keys.indexOf(39) != -1;
            var down = keys.indexOf(40) != -1;
    
            /* What direction? */
            var x = left ? "negative" : right ? "positive" : false;
            var y = up ? "negative" : down ? "positive" : false;
            /* Are we heading to a different direction?*/
            if(lastX != x || lastY != y) animation.move(x, y);
            lastX = x;
            lastY = y;
        }
    
        //Add event listener
        var eventType = "keydown";window["on"+eventType] = keyCheck;
    })();
    

    At the end of the anonymous function, the keydown event listener is added. This event is fired only once (when the key is pressed down). When a second key is pressed fast enough, the code recognises two key strokes after each other, and calls keyCombi().

    I have designed keyCombi to be intelligent, and only call animation.move(x,y) when the values are changed. Also, I’ve implemented the possiblity to deal with two directions at a time.

    Note: I have contained the functions within an anonymous function wrapper, so that the variables are not defined in the global (window) scope. If you don’t care about scoping, feel free to remove the first and last line.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically, what I'm trying to create is a page of div tags, each has
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have thousands of HTML files to process using Groovy/Java and I need to
I am trying to loop through a bunch of documents I have to put
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm making a simple page using Google Maps API 3. My first. One marker
I am trying to understand how to use SyndicationItem to display feed which is
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.