Naveed Ahmed Naveed Ahmed - 2 months ago 6
CSS Question

How to make li clickable without affecting inner anchor?

I have a list of products for which I am using below li:

When user clicks anywhere on the li I want use to send to product details page e.g. /product/id/. When user mouse over the li I also display an icon which when clicked allows users to add product in Favorites.

<li class="media">
<div class="media-left">
<a href="/product/123/">
<div class="thumb">
<img src="/images/company-logo.jpg">
<div class="media-body">
<div class="item-actions autohide pull-right">
<a title="Add to Favorites"><i class="material-icons">favorite</i></a>
<div class="media-heading b">
<a href="/product/123">Demo Product</a>
<div class="text-sm">
<div style="height:16px;overflow:hidden;">Demo Manufacturer</div>

I know I can make the whole li clickable and send user to product details page using javascript.

<li (click)="sendToproductDetailsPage(123)">

But the issue with this approach is that when I click on Favorite icon, it also send users to product details page.

Can anyone please guide how to achieve this with pure JavaScript?


You clearly have an event handler for the "Favorite" a link that handles adding the thing to the favorites. Have that event handler stop propagation. Since the click stops as of that a, it never bubbles up to the li, and you don't have to worry about it triggering the li's click handler.

If you're hooking up events through addEventListener, your handler gets an event object that has stopPropgation, so:


If you're using onxyz-style event handlers, return false from the handler; it does the same thing stopPropgation does (more on my blog: The true story on return false).