7

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>
clarkk
  • 27,151
  • 72
  • 200
  • 340
  • Here's the solution https://stackoverflow.com/questions/9183381/how-to-have-click-event-only-fire-on-parent-div-not-children `if (e.target !== e.currentTarget) return` – Alex78191 Sep 20 '22 at 13:49

3 Answers3

10

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
} 
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
4

you can use this:

if(event.toElement != this)
    return;
  • Example code for Jquery: `$('.mybutton').click( function(e){ if(e.toElement==$(this)[0]) { // do stuff } });` – Avatar Feb 01 '21 at 15:05
0

To make it work only on direct clicks, do this:

for jquery:

$(".background").click(() => {
    console.log("background got clicked");
});

$(".background > *").click((event) => {
    event.stopPropagation();
});

for vanilla js:

document.querySelector(".background").addEventListener("click", (event) => {
    console.log("background got clicked");
});

let backgroundChildren = document.querySelectorAll(".background > *");

backgroundChildren.forEach(element => {
    element.addEventListener("click", (event) => {
        event.stopPropagation();
    });
});