unicornquestion unicornquestion - 1 year ago 76
Javascript Question

JS - Only trigger document.onkeydown function if input is not selected

I'm currently calling the

document.onkeydown
function to trigger a movement function using the W,A,S,D keys.

It is working fine using the following code:

document.onkeydown = function(event){
if(event.keyCode === 68){
socket.emit('keyPress', {inputId: 'right', state: true});
}
else if(event.keyCode === 83){
socket.emit('keyPress', {inputId: 'down', state: true});
}
else if(event.keyCode === 65){
socket.emit('keyPress', {inputId: 'left', state: true});
}
else if(event.keyCode === 87){
socket.emit('keyPress', {inputId: 'up', state: true});
}
}

document.onkeyup = function(event){
if(event.keyCode === 68){
socket.emit('keyPress', {inputId: 'right', state: false});
}
else if(event.keyCode === 83){
socket.emit('keyPress', {inputId: 'down', state: false});
}
else if(event.keyCode === 65){
socket.emit('keyPress', {inputId: 'left', state: false});
}
else if(event.keyCode === 87){
socket.emit('keyPress', {inputId: 'up', state: false});
}
}


My only problem with this is when the user types a chatmessage into the html input then the charackter would still move.

<input type="text" class="form-control" placeholder="Please enter message..." id="chat-input">


Which way should should be used to check if the html is selected/active or not?

Answer Source

The simplest way would probably be to test the active element with document.activeElement. You can use document.activeElement.tagName and test to see if it is an input tag.

So something like

document.onkeydown = function(event){
    if (document.activeElement.tagName !== "input") {
        if(event.keyCode === 68) {
            //...
        }
    }
}

That said, I recommend using addEventListener instead of attaching to onkeydown property. document.addEventListener('keydown', function() { /*...*/ }); is better. That way you don't overwrite any other events for the document. It's just better practice. I'd only use document.onkeydown if you need to support IE8 or lower.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download