Search code examples
javascripthtmlhyperlinkonclickhref

How to prevent redirect after hyperlink click?


I have following html+ js code:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>

<a href="#" id=key onclick="func(0)">foo</a>

</body>

<script type="text/javascript">
function func(k){
    alert(1);
    return false;
}   
</script>
</html>

Can you explain how to refactor following code that after click on href code func executes but # doesn't add to the URL and page shouldn't be reload?


Solution

  • Use javascript:void(0); instead of # as follows:

    <a href="javascript:void(0);" id=key onclick="func(0)">foo</a>
    

    Using the void operator in the href attribute of the anchor tag ensures that the browser will still display it the same way as any other anchor tag (depending on your CSS settings, this is generally a blue underlined text that changes the cursor when hovered over... etc), prevents the page redirecting to a URL that's just effectively the same page but with the added hash character (#) at the end of the address line, while also makes your onclick event to fire.