jQuery Press D & A to Slide

Use keydown to make an element move.

by Colin Soderstrom

HTML

<p class="ttle">Click this Result box then press D to slide right and A to slide left.</p>
<div id="lftRgt"></div>

CSS

.ttle {
    font-family: arial;
}
#lftRgt {
    background-color: #ff0000;
    width: 100px;
    height: 100px;
    position: relative;
}

JavaScript

var Xpos = 0;

$(document).keydown(function(e){
    if (e.keyCode == 68){ //D Right
        $('#lftRgt').animate({
            left: 100+Xpos+'px'
        }, 500 );
        Xpos = Xpos+100;
    }
    if (e.keyCode == 65){ //A Left
        $('#lftRgt').animate({
            left: -100+Xpos+'px'
        }, 500 );
        Xpos = Xpos-100;
    }
});