David Grabon
David Grabon

Reputation: 107

Checking if the specific key is pressed on a looping function

So my script has a looping function that is designed to print out a string when a specific key (the a key) is pressed down, and if its not then it prints out a different string, so that when the key is held it will continuously print the first string. I have tried about 30 different ways to make it register but nothing will work. The function begins running from another function, NOT when I press the button on a div so I don't want to hear any onKeyDown to run this function, I need it constantly running and checking when the key is pressed

function legs(interval, key, text) {

    if (foot == true) {
        text.innerHTML = 'Left Foot<br/><br/>' + text.innerHTML;
    } else {
        text.innerHTML = 'Trip!<br/><br/>' + text.innerHTML;
    }

    setTimeout(function(){legs(interval, key, text)},interval);
}

The interval its passed to with is 500, the key is 'a', and the text is the div that its printing the string out to. Can anyone help me with this please?

Upvotes: 0

Views: 157

Answers (2)

brouxhaha
brouxhaha

Reputation: 4093

Use a boolean variable keyPressed. Use a keydown event on the document to watch for the a key. If it's pressed, change the variable keyPressed = true. Then set keyPressed = false on keyup.

Using jQuery:

var keyPressed = false;

$(document).keydown(function(e){
        var keycode = e.keyCode || e.which;

        //if a key is held down
        if(keycode == 65){
            keyPressed = true;
        }


    });

$(document).keyup(function(e){
        var keycode = e.keyCode || e.which;

        if(keycode == 65){
            keyPressed = false;
        }
    });

Using plain ol' JavaScript:

document.onkeydown = function(e){
        var keycode = e.keyCode || e.which;

        //if a key is held down
        if(keycode == 65){
            keyPressed = true;
        }


    }

document.onkeyup = function(e){
        var keycode = e.keyCode || e.which;

        if(keycode == 65){
            keyPressed = false;
        }
    }

Upvotes: 1

Max Meijer
Max Meijer

Reputation: 1729

You could add an isAKeyDown flag, like this:

var isAKeyDown;

Then add an onkeydown handler where you check if the key pressed is the A key, if so set isAKeyDown to true. In the onkeyup handler set it to false again.

Upvotes: 1

Related Questions