Skip to content
Advertisement

How to stop the default behavior of a link from a child element

I am making an ad card using bootstrap, I’ve placed the card inside <a> element so that when the user clicks the card, the whole card will act as a link.

I have a favorite link that marks the ad as a favorite for the user. The problem is, since the whole card is a link, whenever I click the fav button, the parent link is clicked which is meant to go to the page of the ad, I want to stop that behavior and instead run whatever function favorite button has assigned to it.

Basically I want to stop the behavior of parent link.

My HTML for card:

JavaScript

My JS present in an external file:

JavaScript

Advertisement

Answer

You can prevent the default event if the button is clicked inside the anchor element’s click event handler function like the following way:

JavaScript

Demo:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement