Click - only on "direct" onclicks

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

div.click () should only be triggered when the user clicks inside the div, but outside the input element

<div style="width:400px; height:200px">
<input type="text" style="width:50px" />
</div>
+5
source share
2 answers

You have two options:

Attach the event handler clickto the input element and do not fire the event by calling it by calling event.stopPropagation() [docs] :

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

OR

Inspect the event.target [docs] in the event handler clickattached to divwhether the target is an element inputor not. Sort of:

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

:

if(event.toElement != this)
    return;
+1

All Articles