Refinance now before rates go up! Get multiple rate quotes at GetMyLender.com.

How to Prevent Default Behavior of Anchor Tag using JavaScript and jQuery

Many times we need to use anchor tag in html coding. For anchor tag we assign href attribute with URL. So that whenever user click on that it will redirect to URL given as a value of href attribute. But how to prevent this default functionality?

We can prevent this default behavior of anchor tag using JavaScript or jQuery.

Simply, if we assign # to the href then after clicking on it will not redirect to any URL but it will jump to top of screen.

<a href="#"> Click Here </a>

So, how to prevent that behavior?

- We can prevent default behavior of anchor tag by assigning javascript:void(0) in href then it will not redirect to any URL

<a href="javascript:void(0)"> Click Here </a> Using JavaScript

Suppose anchor tag is defined as follows

<a href="http://blog.shivajisoft.com" id="webLink">Anchor tag Prevent using JavaScript code</a>

By writing return false we can override default behavior of the element.

<script type="text/javascript"> document.getElementById("webLink ").onclick = function () { // do your own work return false; }; </script> Using jQuery

Suppose anchor tag is defined as follows

<a href="http://blog.shivajisoft.com" id="webLink">Anchor tag Prevent using JavaScript code</a>

By writing event.preventDefault() we can override default behavior of the element.

$(document).ready( function(e) { $('#webLink').click ( function(e) { // stop its defaut behavior e.preventDefault(); // do your own work }); });
Conclusion :

I hope that this article would have helped you in understanding to Prevent default behavior of anchor tag using JavaScript and jQuery. Your feedback and constructive contributions are always welcome.


No comments:

Post a Comment