Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event handler on body but not on input

Tags:

javascript

I have the following event handler

document.addEventListener('keydown', handleBodyKeyDown, false);

HOW DO i prevent it from occurring when inside a input box

like image 715
aWebDeveloper Avatar asked Aug 29 '11 13:08

aWebDeveloper


2 Answers

Within your handleBodyKeyDown function, check if

 event.target.tagName.toUpperCase() == 'INPUT'

(or 'TEXTAREA').

Note: For older versions of IE, use event.srcElement.tagName.

Like so:

document.addEventListener('keydown', handleBodyKeyDown, false);

function handleBodyKeyDown(event)
{
    var e = event || window.event,
        target = e.target || e.srcElement;

    if (target.tagName.toUpperCase() == 'INPUT') return;

    // Now continue with your function
}

P.S. Why are you using addEventListener if you have jQuery on the page? In jQuery, all of this gets sorted out for you:

$(document).on('keydown', ':not(input)', function(e)
{
    // Your code goes here...
});
like image 75
Joseph Silber Avatar answered Oct 11 '22 03:10

Joseph Silber


In your handleBodyKeyDown method, check to see if the event originated on an input element:

function handleBodyKeyDown(event) {
    if (event.target.tagName.toUpperCase() === 'INPUT') {
        return; // do nothing
    }

    // do the rest of your code
}

Note that the toUpperCase call is necessary because the conditions that determine the case of the tagName property are quite complicated and sometimes all but uncontrollable.

See event.target at MDN.

like image 22
lonesomeday Avatar answered Oct 11 '22 03:10

lonesomeday