Search code examples
javascriptjqueryhtmlonclickhref

Disable HREF by onclick inside


How can I disable the a href if an element with an onclick function is fired within the <a> element?

I tried event.preventDefault();, but it doesn't seem to do anything.
How can I solve this?

$(function() {
  $(".inside > .fa").click(function(event) {
    event.preventDefault();
    alert("TEST");
  });
});
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href='/'>
  <div class='button'>
    <div class='inside'>
      <i class="fa fa-globe"></i>
    </div>
  </div>
</a>


Solution

  • The click still bubbles upwards. Use event.stopPropagation(); instead. You are using event.preventDefault() on an element that has no default click behaviour, so it does nothing.

    $(function() {
      $(".inside > .fa").click(function(e) {
        e.stopPropagation();
        console.log(e.target);
      });
    });
    a {
      display: block; /* required otherwise you cannot have block level elements like div inside a */
    }
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href='https://google.com' target="_top">
      <div class='button'>
        <div class='inside'>
          <i class="fa fa-globe"></i>
        </div>
      </div>
    </a>