Development and Design

Avoid Web Pages Jumping To Top While Using OnClick Event

When you use empty or ‘#’ reference in a href of a anchor tag (<a href=”#”></a>) to define any onclick or other functions like hover, ondblclick, you can find that the page jumps to the top or else it reloads again. I came across this problem when I tried to implement a tabs like design using JQuery’s “.click()” function. When ever the tab link (with # in the href) get pressed, JQuery comes in to play and hides the visible tab and shows another tab in the line according to the button clicked.

This problem persists over any where # link is used. The below code explains the problem. I am not certain why it happens, it may happen because the browser tries to find the # link, due to the failure it pose top of the page in the view port, or it may happen because the browser tries to re-render or redraw the page again using the available html source. While using empty href, you can able to see the page reloads, every time the particular click action is made irrespective of what functions used inside the onclick or any other functions used.

[code]<a href="#" onclick="alert(‘After you click Ok, the page will jump back to the top’)">Click to see the above code in action</a> [/code]

Click to see the above code in action

The above code demonstrates the problem. The solution to avoid this is very simple. You have to replace # or empty href with a void JavaScript function ( JavaScript:void(0);  ). The demo and the code is given below.

[code]<a href="JavaScript:void(0);" onclick="alert(‘This stops page jumping’)">Click to see the above code in action</a> [/code]

Click to see the above code in action

So here after never use empty or # reference in  anchor tag, particularly when you design some dynamic page or using transitions with the help of JQuery or any other JavaScript libraries.

About the author

Sakthi Tharan

Alpha Geek | Blogger by interest | Former Web Developer & Designer | Research Scholar | Likes to share what he learned.