user2878971
user2878971

Reputation:

Disable click propagation for href

This code snippet explains my case:

$("#b").click(function(e) {
  e.stopPropagation();
});

$("#b").click(function() {
  alert("trigger div");
});
a {
  display: block;
  position: relative;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0;
  left: 0;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="stackoverflow.com" id="a">
  <div id="b">Test</div>
</a>

The problem is that I only want to trigger the click function from the div and not the href from the a tag. In a similar question I found event.stopPropagation(), but that does not work in this case.

Upvotes: 1

Views: 1462

Answers (3)

Tomer Wolberg
Tomer Wolberg

Reputation: 1356

without javascript:

#a {
  display: block;
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
}
<a href="stackoverflow.com" id="a">
<a href="#"><div onclick="alert('trigger div')">test</div></a>
</a>

Upvotes: 1

Osama
Osama

Reputation: 3040

$("#a").click(function (event) {
    event.preventDefault();
});

$("#b").click(function (event) {
    event.stopPropagation();
    alert("trigger div");
});

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

You need to prevent the default click event action using event.preventDefault() method.

$("#b").click(function(e) {
  e.preventDefault();
  alert("trigger div");
});
a {
  display: block;
  position: relative;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0;
  left: 0;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="stackoverflow.com" id="a">
  <div id="b">Test</div>
</a>

Upvotes: 2

Related Questions