0

I have an element with an hyperlink. Inside the are also buttons, which should trigger their button actions, without triggering the hyperlink.

Demo code:

<a href="element.html">
 <div class="element_card">
   This is an card for an element with an hyperlink over the card.
    <button type="button" onclick="like_element()">
      Like the element but do not trigger the hyperlink.
    </button>        
 </div>
</a>

How can I disable the hyperlink for the button or cancel the event, so that the button area ia only triggering the onclick function for the button but not the hyperlink.

user1482309
  • 289
  • 3
  • 16
  • you will need javascript, but what have you tried until now, do you have some JS code? is it not working? – Calvin Nunes Jan 30 '20 at 14:22
  • 5
    Your HTML is invalid. Buttons can't be descendants of anchors – j08691 Jan 30 '20 at 14:24
  • @j08691 why not? A block level anchor is akin to a div. OP just would need to stop the propagation when handling the button's click event. – GetSet Jan 30 '20 at 14:25
  • @GetSet I didn't make the rules – j08691 Jan 30 '20 at 14:26
  • Technically it will work, but doesn't follow the html spec. A workaround is to use a wrapping `div` with your `a` and `button` tags as children, then use css positioning to make the `button`s appear as if they are inside the `a` – Dane Stevens Jan 30 '20 at 14:29

4 Answers4

3

You can use event.stopPropagation() to block the click from travelling up the chain.

Dane Stevens
  • 465
  • 3
  • 7
1

You can use event.stopPropagation() to prevent further propagation of the current event in the bubbling phases.

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

Or Ben-Yossef
  • 399
  • 2
  • 17
0

See if this works for you.

The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented) See if this works for you.

Answer

<a href="element.html">
 <div class="element_card">
   This is an card for an element with an hyperlink over the card.
    <button type="button" onclick=" return like_element()">
      Like the element but do not trigger the hyperlink.
    </button>        
 </div>
</a>
Abhishek Pakhare
  • 476
  • 1
  • 4
  • 15
0

using this inside href javascript:void(0)

function like_element(){
  console.log('working....!')
}
.element_card{
background-color: green;
}
<a href="javascript:void(0)">
 <div class="element_card">
   This is an card for an element with an hyperlink over the card.
    <button type="button" onclick=" return like_element()">
      Like the element but do not trigger the hyperlink.
    </button>        
 </div>
</a>
vijay
  • 186
  • 2
  • 12