jQuery HTML Element How to - Prevent anchor's href from opening link but still execute other bind events








Question

We would like to know how to prevent anchor's href from opening link but still execute other bind events.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--from  w  ww.  j av  a 2 s .  c o m-->
    $("a").click(function() {
        return false;
    });
    $(".toolbar a").click(function() {
        console.log("Do something");
    });
});
</script>
</head>
<body>
  <a href="http://www.java2s.com">Test</a>
  <div class="toolbar">
    <a href="#test2">Test 2</a>
  </div>
</body>
</html>

The code above is rendered as follows: