user1482309
user1482309

Reputation: 309

Button inside hyperlink div

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.

Upvotes: 1

Views: 912

Answers (4)

vijay
vijay

Reputation: 306

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>

Upvotes: 0

Or Ben-Yossef
Or Ben-Yossef

Reputation: 419

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

Upvotes: 1

Abhishek Pakhare
Abhishek Pakhare

Reputation: 494

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>

Upvotes: 0

Dane Stevens
Dane Stevens

Reputation: 535

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

Upvotes: 4

Related Questions