Alvizgo
Alvizgo

Reputation: 25

how to run a code when Left Arrow or Right Arrow Key Is Triggered on the keyboard

How to run a code in javascript when Left Or Right Arrow Keys is Triggered on the keyboard?

I am kinda Newbie to programming.

Can someone please guide me?

Upvotes: 1

Views: 142

Answers (4)

Ishan Jain
Ishan Jain

Reputation: 8171

You need to attach event handler for tracking the key-board events

document.addEventListener("keydown", keyDownevent, false);

function keyDownevent(e) {
var keyCode = e.keyCode;
    if (e.keyCode === 37) {//right  
        // Your Code             
    }  
    else if (e.keyCode === 38) {//UP              
        // Your Code             
    }
    else if (e.keyCode === 39) {//left 
        // Your Code 
    }
    else if (e.keyCode === 40) {//DOWN 
       // Your Code 
    }     
}

Working Example

It's simple with Jquery:

Try this :

$(document).keydown(function (e) {
        e.stopImmediatePropagation();        
        if (e.keyCode === 37) {//right  
             // Your Code             
        }  
        else if (e.keyCode === 38) {//UP              
            // Your Code             
        }
        else if (e.keyCode === 39) {//left 
            // Your Code 
        }
        else if (e.keyCode === 40) {//DOWN 
            // Your Code 
        }               
    });

Upvotes: 1

Raúl De Zamacona
Raúl De Zamacona

Reputation: 159

First you need to get the value of the key you pressed, with jquery it is done like this:

$(‘#keyval’).keyup(function(e) {
    console.log(e.which)
});

Then you do the test to see what value those keys has and then check for keyup event, check if it has than value and then do the action, like this:

$(document).keypress(function(e) {
    if(e.which == //arrow value) {
        // your action
    }
});

I have not tested it but it must work.

Upvotes: 0

thedjaney
thedjaney

Reputation: 1126

If you are new to Javascript, then may I advise on using libraries to make things easier (because you may end up fixing a lot of cross-browser issues) :) jQuery is a good one, here are some keyboard events. http://api.jquery.com/category/events/keyboard-events/

Upvotes: 0

Aljon Ngo
Aljon Ngo

Reputation: 251

    function leftpress() {
        //do action
    }

    function rightpress() {
        //do action
    }

    document.onkeydown = function(evt) {
        evt = evt || window.event;
        switch (evt.keyCode) {
            case 39://left arrow
                leftpress();
                break;
            case 37://right arrow
                rightpress();
                break;
        }
    };

this is the exact code, try it ..

-you can ask me again if you need help.

Upvotes: 2

Related Questions