Joseph118
Joseph118

Reputation: 505

differentiate the clicks between parent and child using javascript/jquery

I have 2 elements nested called blanket and blanket-content and I want to recognize the clicks done to the parent alone.

<div id="blanket">
    <div id="blanket-content"></div>
</div>

The issue that I'm having is that when I'm clicking the child it is triggering the parent on click. I've tried different methods yet I was unsuccessful. I have tried these to play around with my code;

$('#blanket').on('click', function(ev) {
    alert(ev.currentTarget.id); //
});

^ This triggers the click on div as normal and state the parent id even when the child is clicked.

$('#blanket-content').on('click', function(ev) {
        alert(ev.currentTarget.id);
});

^ This doesn't trigger anything

What I want to achieve is when I click on blanket-content nothing will happen, but when I click on blanket I want to do something.

Upvotes: 4

Views: 1165

Answers (3)

Ronnie
Ronnie

Reputation: 239

Try preventing the Default action, stop propogation doesn't always work if it is still being referenced.

$('#blanket').on('click', function(event){
    $(event).preventDefault();
});

this will stop the default action of a click event and will work well.

for more information, go here

Upvotes: 0

Umesh Sehta
Umesh Sehta

Reputation: 10683

No need to do more. Just add ev.stopPropagation(); inside #blanket-content click event.

<div id="blanket">PARENT
    <div id="blanket-content">CHILD</div>
</div>


$('#blanket').on('click', function(ev) {
    alert(ev.currentTarget.id); //
});


$('#blanket-content').on('click', function(ev) {
    ev.stopPropagation();
    alert(ev.currentTarget.id);
});

Check here: https://jsfiddle.net/92jwad1w/

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

One easy solution is to stop the event propagation in a click handler of the blanket-content, so that it will trigger the parent element's click handler.

You can use Event.stopPropagation() to do that

$('#blanket').on('click', function(ev) {
  alert(ev.currentTarget.id); //
});


$('#blanket-content').on('click', function(ev) {
  ev.stopPropagation()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blanket">blanket
  <div id="blanket-content">blanket-content</div>
</div>


Another solution(why) is to check whether the click happened in the blanket-content element inside the blanket click handler

$('#blanket').on('click', function(ev) {
  if (!$(ev.target).closest('#blanket-content').length) {
    alert(ev.currentTarget.id); //
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blanket">blanket
  <div id="blanket-content">blanket-content</div>
</div>

Upvotes: 3

Related Questions