Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event in parent and children

Tags:

jquery

I have a parent element DIV that has children div elements. I have separate click implementations for parent and its children.

<div id="mainContainer">

    <div id="childContainer">    
    </div>

     <div id="childContainer2"> 
    </div>

</div>

$('#mainContainer').click(function () {

        console.log('main container');

    }).children().click(function () {
        console.log('childen');
        return false;
    });

    $('#childContainer2').click(function () {

        console.log('child container 2');

    }); 

This is working fine. but if I click a child then the event runs twice which is how it is supposed to work. My question is - Is there a way that I can explicitly write event to parent that would not affect children so that children need not execute click function twice?

like image 347
KrishnaDhungana Avatar asked Dec 13 '13 07:12

KrishnaDhungana


People also ask

How do you only trigger parent click event when a child is clicked?

If your child element is located inside your parent element you could also just add this CSS property. This way the click directly triggers the parent's click event listener.

How do you prevent click event on parent element?

By a adding an onClick function for the child modal (content div) mouse click events are prevented to reach the 'closeLogin' function of the parent element.

What is a click event?

An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.

How do I prevent a parent's onClick event from firing when a child anchor is clicked react JS?

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.


2 Answers

yes you can just, change the order of binding the events and to stop propagation use stopImmediatePropagation

consider this fiddle

$('#childContainer2').click(function (e) {       
       alert('child container 2'); 
        e.stopImmediatePropagation()
     return false;
    }); 
$('#mainContainer').click(function () {
alert('main container');

    }).children().click(function (e) {
       alert('childen');
        return false;
    });
like image 139
A.T. Avatar answered Oct 20 '22 03:10

A.T.


You can use use event.stopPropagation:

children().click(function (e) {
    e.stopPropagation();
    console.log('childen');
    return false;
});

to prevent event buble up

like image 3
Felix Avatar answered Oct 20 '22 04:10

Felix