'How to prevent default when click on icon inside a anchor link list?

I have a link list with namnes that loads a new page if you click on the li.

And besides the name I have a heart icon.

And when I click on the heart I want to prevent the default behavior on the link and just open an alert instead(not loading the page). And if I click anywhere else on the li then it should load the page as expected.

I have this structure now.

<a href="page.html">  
    <li>
      <div class="item-content">
        <div class="item-inner">
          <div class="item-title">Anna Andersson</div>
          <div class="item-after">

        <i class="f7-icons fodelsedag">heart_fill</i>

          </div>
        </div>

      </div>
    </li>
    </a>

And here is the js code.

$$(document).on('click', '.fodelsedag', function (e) { 

//so how can I prevent the default on the li here?
alert("test alert")


});

Thanks for any input!



Solution 1:[1]

You will need to change your markup so it is valid. li must be the direct descendant of your ol or ul element, you will need your a tag inside the li element:

<ul><li>  
 <a href="page.html" class="link">
  <div class="item-content">
    <div class="item-inner">
      <div class="item-title">Anna Andersson</div>
      <div class="item-after">
        <i class="f7-icons fodelsedag">heart_fill</i>
      </div>
    </div>
  </div>
</a>
</li>
</ul>

and then your script needs to prevent bubbling:

$(document).on('click', '.link', function (e) {
    e.stopPropagation();
    if ($(e.target).hasClass('fodelsedag')) {
        e.preventDefault();
    }
    alert("test alert");
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1