brettgag
brettgag

Reputation: 211

jQuery call event on keydown or keyup

I am trying to change the color of a div element on a keydown and keyup but i just cant seem to get it to work. Ive check every example i can find on the internet but my code will just not seem to work.

All of the examples i find seem to use a form input text field as a target for the keypress. I dont want to do that. here is my code:

$(document).keydown(function(e){
    if(e.which == 'A')
    {
        alert('key was pressed');
        $(#k1).css('background-color', "blue");
    }
});

My thought is that $(document) is not the correct thing to have there because the function is never called. But because all the examples i find use a textfield input, i just cant figure out what to put there.

Upvotes: 1

Views: 2079

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206008

LIVE DEMO

$(document).keydown(function(e){
    if(e.which == 65){
        alert('Pressed key was: '+ e.which );
        $("#k1").css( { backgroundColor:"blue" } );
    }
});

If you need $('input') instead of $(document) feel free to use it,
65 is the event.which for A

Upvotes: 4

Ross Joo
Ross Joo

Reputation: 180

Your which condition isn't valid. Should be 65 as others mentioned.

http://api.jquery.com/keypress/

If you scroll down, you can type in any key and see the which value of each key.

Alternatively, you can do

console.log(e.which);

Upvotes: 0

Travis J
Travis J

Reputation: 82267

Couple of things. Firstly, the event.which will return a number which correlates to a key. And secondly, your jquery target needs to be a string. So, change the =='A' to ==65 and $(#k1) to $("#k1") and it will work. Here is a demo: http://jsfiddle.net/AeBtV/

js

$(document).keydown(function(e){
 if(e.which == 65)
 {
    alert('A key was pressed');
    $("#k1").css('background-color', "blue");
 }
});

Note on key code numbers:

The range is from 65-90 for A to Z. Thus A is 65, Z is 90, and R is 82.

Upvotes: 1

Bob McCown
Bob McCown

Reputation: 127

I've trapped keyup and keydown events using .live:

$("#my_id").live('keydown',function(event) {

...

});

Upvotes: 0

Related Questions