0

I have a link and inside this link an icon, I'd like to be able to click on the icon without triggering the link.

For example:

enter image description here

This whole block is a link and I have the green square inside it. What I want to do is to make the green square ignore the parent link. Would that be possible?

Just to be clear, I don't want to disable the link, I want it working in the pink area and ignored only by the green square.

So, some people suggested this post, but it doesn't answer my question: How to disable HTML links

Here is an example of my code followed by a codepen with it.

HTML:

<a href="https://www.facebook.com/">
  <div  class="container">
       <div onClick="dontCallLink()" class="subDiv"></div>
  </div>
</a>

JS:

function dontCallLink(event) {
  document.getElementsByClassName('subDiv')[0].style.backgroundColor = "red"
}

CSS:

.container {
  height: 250px;
  width: 200px;
  background-color: pink;
}

.subDiv {
  width: 30px;
  height: 30px;
  background-color: green;
  margin-left: 160px;
  margin-top: 200px;
  position: absolute;
  cursor: default;
}

https://codepen.io/WegisSilveira/pen/rNLQMXV

Berg_Durden
  • 1,531
  • 4
  • 24
  • 46
  • why dont you just set it on absolute position with z-index bigger than 0? – Aristeidis Karavas Nov 11 '20 at 19:05
  • I have an answer to a very similar question here: [Is it possible to stop the browser from following the link when the onclick of the child element fires?](https://stackoverflow.com/a/64773283/2430549), for a question all the way from 2009. – HoldOffHunger Nov 11 '20 at 19:39

1 Answers1

1

The solution is quite simple, I just needed to use event.preventDefault() after calling dontCallLink().

The final code is this:

HTML:

<a href="https://www.facebook.com/">
  <div  class="container">
       <div onClick="dontCallLink(event)" class="subDiv"></div>
  </div>
</a>

JS:

function dontCallLink(event) {
  document.getElementsByClassName('subDiv')[0].style.backgroundColor = "red"
  event.preventDefault() // =>  Just prevent default after doing what I want with the function, it will prevent the event click to bubble up.
}

CSS:

.container {
  height: 250px;
  width: 200px;
  background-color: pink;
}

.subDiv {
  width: 30px;
  height: 30px;
  background-color: green;
  margin-left: 160px;
  margin-top: 200px;
  position: absolute;
  cursor: default;
}
Berg_Durden
  • 1,531
  • 4
  • 24
  • 46