Lazaro Gamio
Lazaro Gamio

Reputation: 859

jQuery keyboard events on DOM elements

I'm building a project where I will have two divs which have their CSS switched up on different individual keypresses.

I am using this jQuery library: https://github.com/jeresig/jquery.hotkeys/

You can see a simple demo here: http://lazarogamio.com/projects/key_test/

Here is my HTML:

<div class="test_box" id="red"></div>

<div class="test_box" id="green"></div>

My CSS:

.test_box {
width: 200px;
height: 200px;
border: 2px solid #000;
margin: 20px;
float: left;
}

.red {
background-color: red;
}

.green {
background-color: green;
}

And my jQuery:

function keymap(){

$(document).bind('keydown', 'r', function (evt){
    $('#red').toggleClass('red');
    });

$(document).bind('keydown', 'g', function (evt){
    $('#green').toggleClass('green');
    });
};

$(document).ready(keymap);

At the moment, the keydown event is working, but for every key, and for both divs. I originally had each div controlled by a separate function, but my results were the same. I also tried to map other keys to do nothing, to no avail. My hunch is that I am not targeting the keys properly, or perhaps not binding the function to the correct object?

Upvotes: 1

Views: 237

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

You're including hotkeys before you include jQuery. It needs to be the other way around. Currently, you're just binding to keydown like normal and the hotkeys include has no effect.

If you include jQuery first, it should work as you expect:

http://jsfiddle.net/ExplosionPIlls/GGvrd/

Upvotes: 1

Related Questions