17 May 2016

Prevent hyperlink click behavior using jQuery


Often web devs (you and me), put an anchor tag and write a custom function for its onclick event. The href field will get assigned with a "#" and you are happy to see your function getting called on every click of the hyperlink. So far so good.

It will be a little later that you notice a jerk when you click on the hyperlink, which puts your page scrolled back to the top. This is a kind of an undesired behavior which you do not want to see.

Well, the solution is simple. Just add preventDefault() call at the start of the onclick handler.  The sample code below shows an example.

<a href="#" id="link">Click here</a>
.
.
.
$("#link").click(function(param){
param.preventDefault();
//do stuff
});

No comments: