Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click - only on "direct" onclicks

Tags:

jquery

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>
like image 772
clarkk Avatar asked Jun 28 '11 20:06

clarkk


2 Answers

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
} 
like image 193
Felix Kling Avatar answered Nov 06 '22 20:11

Felix Kling


you can use this:

if(event.toElement != this)
    return;
like image 36
Salvatore Pruiti Avatar answered Nov 06 '22 20:11

Salvatore Pruiti