davideghz
davideghz

Reputation: 3685

click on link in a div without firing div.click event

Given the following html:

<div id="mydiv">
  <a href="#">link</a>
</div>

<div id="target">
  target
</div>

and the following js:

$('#mydiv').click(function() {
  $('#target').css('background-color', 'blue');
});

What can I do to prevent clicks on link to fire click event on parent div without affecting the functionality of clicks on div?

Here a pen to show what I mean: https://codepen.io/davideghz/pen/bWdVWg

Upvotes: 3

Views: 1735

Answers (1)

tao
tao

Reputation: 90148

You need to call .stopPropagation() on your click event to prevent it bubbling up:

$('#mydiv a').click(function(e) {
  e.stopPropagation();
});
$('#mydiv').click(function(e) {
  $('#target').css('background-color', 'blue');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">
  <a href="#">link</a>
</div>

<div id="target">
  target
</div>

.stopPropagation() is not jQuery. Here's how to do the above script in vanilla:

document.getElementById('mydiv').addEventListener('click',function(e) {
  if (event.target.tagName.toLowerCase() === 'a') {
    e.stopPropagation();
  } else {
    document.getElementById('target').style.backgroundColor = 'blue';
  }
});
<div id="mydiv">
  <a href="#">link</a>
</div>

<div id="target">
  target
</div>

Upvotes: 3

Related Questions