clarkk clarkk - 1 month ago 7
jQuery Question

click - only on "direct" onclicks

If you put a .click() on a div element and you got an input element in the div.. how can you then omit the .click() if the user clicks on the input?

The div.click() only has to trigger when the user click inside the div, but outside the input element

<div style="width:400px; height:200px">
<input type="text" style="width:50px" />
</div>

Answer

You have two choices:

Attach a click event handler to the input element and prevent the event from bubbling up by calling event.stopPropagation() [docs]:

$('input').click(function(event) {
    event.stopPropagation();
});

OR

Inspect the event.target [docs] in the click event handler attached to the div whether the target is the input element or not. Something like:

if(event.target.nodeName !== 'INPUT') {
    // do something
}