[jquery] How to have click event ONLY fire on parent DIV, not children?

I have a DIV with a classed foobar, and a few DIVs inside that DIV that are unclassed, but I suppose they are inheriting the foobar class:

$('.foobar').on('click', function() { /*...do stuff...*/ });

I want that to fire off only when clicking somewhere in the DIV but not on its children DIVs.

This question is related to jquery events onclick

The answer is


You can use bubbling in your favor:

$('.foobar').on('click', function(e) {
    // do your thing.
}).on('click', 'div', function(e) {
    // clicked on descendant div
    e.stopPropagation();
});

You can use event.currentTarget. It will do click event only elemnt who got event.

_x000D_
_x000D_
target = e => {_x000D_
    console.log(e.currentTarget);_x000D_
  };
_x000D_
<ul onClick={target} className="folder">_x000D_
      <li>_x000D_
        <p>_x000D_
          <i className="fas fa-folder" />_x000D_
        </p>_x000D_
      </li>_x000D_
    </ul>
_x000D_
_x000D_
_x000D_


$(".advanced ul li").live('click',function(e){
    if(e.target != this) return;
    //code
    // this code will execute only when you click to li and not to a child
})

I had the same problem and came up with this solution (based on the other answers)

 $( ".newsletter_background" ).click(function(e) {
    if (e.target == this) {
        $(".newsletter_background").hide();
    } 
});

Basically it says if the target is the div then run the code otherwise do nothing (don't hide it)


//bind `click` event handler to the `.foobar` element(s) to do work,
//then find the children of all the `.foobar` element(s)
//and bind a `click` event handler to them that stops the propagation of the event
$('.foobar').on('click', function () { ... }).children().on('click', function (event) {
    event.stopPropagation();
    //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler)
});

This will stop the propagation (bubbling) of the click event on any of the children element(s) of the .foobar element(s) so the event won't reach the .foobar element(s) to fire their event handler(s).

Here is a demo: http://jsfiddle.net/bQQJP/


My case is similar but this is occasion when you have few foobar-s, and you want to close only one - per one click:

Find parent case

$(".foobar-close-button-class").on("click", function () {
    $(this).parents('.foobar').fadeOut( 100 );
    // 'this' - means that you finding some parent class from '.foobar-close-button-class'
    // '.parents' -means that you finding parent class with name '.foobar'
});

Find child case

$(".foobar-close-button-class").on("click", function () {
    $(this).child('.foobar-close-button-child-class').fadeOut( 100 );
    // 'this' - means that you finding some child class from '.foobar-close-button-class'
    // '.child' -means that you finding child class with name '.foobar-close-button-child-class'
});

_x000D_
_x000D_
// if its li get value _x000D_
document.getElementById('li').addEventListener("click", function(e) {_x000D_
                if (e.target == this) {_x000D_
                    UodateNote(e.target.id);_x000D_
                }_x000D_
                })_x000D_
                _x000D_
                _x000D_
                function UodateNote(e) {_x000D_
_x000D_
    let nt_id = document.createElement("div");_x000D_
    // append container to duc._x000D_
    document.body.appendChild(nt_id);_x000D_
    nt_id.id = "hi";_x000D_
    // get conatiner value . _x000D_
    nt_id.innerHTML = e;_x000D_
    // body..._x000D_
    console.log(e);_x000D_
_x000D_
}
_x000D_
li{_x000D_
 cursor: pointer;_x000D_
    font-weight: bold;_x000D_
  font-size: 20px;_x000D_
    position: relative;_x000D_
    width: 380px;_x000D_
    height: 80px;_x000D_
    background-color: silver;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
    text-align: center;_x000D_
    margin-top: 0.5cm;_x000D_
    border: 2px solid purple;_x000D_
    border-radius: 12%;}_x000D_
    _x000D_
    p{_x000D_
     cursor: text;_x000D_
  font-size: 16px;_x000D_
   font-weight: normal;_x000D_
    display: block;_x000D_
    max-width: 370px;_x000D_
    max-height: 40px;_x000D_
    overflow-x: hidden;}
_x000D_
<li id="li"><p>hi</p></li>
_x000D_
_x000D_
_x000D_


There's another way that works if you don't mind only targeting newer browsers. Just add the CSS

pointer-events: none;

to any children of the div you want to capture the click. Here's the support tables

http://caniuse.com/#feat=pointer-events


If you can't use pointer-events: none; and are targeting modern browsers you can use composedPath to detect a direct click on the object like so:

element.addEventListener("click", function (ev) {
    if (ev.composedPath()[0] === this) {
        // your code here ...
    }
})

You can read more about composedPath here: https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath


I did not get the accepted answer to work, but this seems to do the trick, at least in vanilla JS.

if(e.target !== e.currentTarget) return;

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to onclick

How to use onClick with divs in React.js React prevent event bubbling in nested components on click React onClick function fires on render Run php function on button click Passing string parameter in JavaScript function Simple if else onclick then do? How to call a php script/function on a html button click Change Button color onClick RecyclerView onClick javascript get x and y coordinates on mouse click