1

I have a .click() on a div.

I added a button in the div and now every time I click the button, the JQuery does the function associated with the div and preforms the action on the button.

I understand why it is doing this. I was wondering if I could make the click listener ignore the children?

Is there already a function/syntax for that or do i need to make one from scratch? The div and the button are called by #id.

1 Answer 1

2

To make the event listener ignore children, you can check that the bound element is the same as the target

$('div').on('click', function(e) {

    if ( e.target === this ) {
       // DIV was clicked, not children
    }

});

Or go the other way, preventing the event from bubbling up

$('div button').on('click', function(e) {
    e.stopPropagation();
});
Sign up to request clarification or add additional context in comments.

4 Comments

The first one is suffice to fulfill this task.
@choz - either one will solve the issue, just noting that there are generally two ways of doing this, stopping the click from bubbling, or just ignore any clicks that didn't come from the bound element
I prefer the first one since we don't need to attach another event handler to the button to avoid bubbling events..
@choz - agreed, that would be my choice as well, but there are instances when the second one is preferable as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.