Search code examples
javascriptjqueryevent-handlingjquery-events

Prevent keypress event trigger when input is in focus


I am currently using a switch to trigger some code when a key is pressed. This isn't the exact code, but its basically what I am using (this is just for the sake of keeping it short and simple on here.)

$(document).keydown(function(e) {
switch(e.keyCode) { 

case 39:
e.preventDefault();
    alert("Arrow Key");

break;

case 37:
   e.preventDefault();
    alert("Arrow Key");
}
});

How can I prevent the events from firing when an input box is in focus?


Solution

  • I think you mean that you want to do e.preventDefault() only if the target element was not an input tag. You can do this like this:

    $(document).keydown(function(e) {
        if (e.target.nodeName.toLowerCase() !== 'input') {
            switch(e.keyCode) { 
                case 39:
                    e.preventDefault();
                    alert("Arrow Key");
    
                    break;
    
                case 37:
                    e.preventDefault();
                    alert("Arrow Key");
            }
        }
    });
    

    e.target is the element where the event originated. Alternatively, you can use jQuery's event delegation API:

    $(document).delegate(':not(input)', 'keydown', function(e) {
        switch(e.keyCode) { 
            case 39:
                e.preventDefault();
                alert("Arrow Key");
    
                break;
    
            case 37:
                e.preventDefault();
                alert("Arrow Key");
        }
    });
    

    Edit Updated my answer to do "not an input" rather than "is an input" checks.