Search code examples
jquerykeystroke

Use jQuery to move DOM element's position across the screen from a keypress?


I would like to move a DOM element once the right arrow key is pressed.

The distance the element moves should be directly proportional to the length of the right arrow keypress.

I was thinking that perhaps I could use this jQuery plugin to find out when the right arrow key is being pressed down, and then add a certain value to the element's left css value to make it seem like it's being moved.

However, I don't know exactly how to make this work. Is it better not to use the plugin and just use the jQuery's methods involved with keystrokes? I just need some help finding out the easiest and most effective way to accomplish this.

Thanks!


Solution

  • May be something like this using only jquery where the div you want to move has ID="d"

    $("body").keydown(function(e) {
        var offset = 5;
        if(e.keyCode == '39') {
            var pos = $("#d").position();
            $("#d").css('left', pos.left + offset);
        }
        else if(e.keyCode == '37') {
            var pos = $("#d").position();
            $("#d").css('left',pos.left - offset);
        }
    });
    

    Note that the div has to have

     position:absolute;