Melissa
Melissa

Reputation: 787

How to change values of div when press key down

I have made divs in my HTML that I use to draw bars with CSS. Now I want the to values change when the user presses the down arrow key.

This is my JavaScript:

var changeIdValue = function(id, value) {
document.getElementById(id).style.height = value;
};

window.addEventlistener("onkeydown", function(e){
if(e.keyCode == 40){
    changeIdValue("balklongwaarde", "60px");
});
}

I don't understand why this is not working.

Upvotes: 0

Views: 895

Answers (2)

Ferdi265
Ferdi265

Reputation: 2969

I know this has been answered already, but if you want to follow your original idea, here's the correct code (because Mritunjay's answer only works for one usage per page).

var changeIdValue = function (id, value) {
        document.getElementById(id).style.height = value;
    };
window.addEventListener('keydown', function (e) {
    if (e.keyCode === 40) {
        changeIdValue('balklongwaarde', '60px');
    }
});
  1. addEventListener is written with a capital L in Listener
  2. 'onkeydown' should be 'keydown' when used with the addEventListener function
  3. You closed your brackets in the wrong order (close if, close function, close function call)

Upvotes: 2

Mritunjay
Mritunjay

Reputation: 25892

You can say something like this

window.onkeydown = function(e){
        if(e.keyCode == 40)
            changeIdValue("balklongwaard", "60px");
        };

Upvotes: 0

Related Questions