salmane
salmane

Reputation: 4849

javascript anchor avoid scroll to top on click

I created a function in javascript that i add to an anchor as such

javascript :

somefunction = function () {alert('foo')}

html :

<a href="#" onclick="return somefunction()">anchor</a>

everytime i click on the anchor the function executes but the screen scrolls to the top

I know i could do this

<a href="javascript:void(0)" onclick="return somefunction()">anchor</a>

but I have seen the first option implemented without this hick up of scrolling up

is there any trick to it?

thank you

Upvotes: 28

Views: 46322

Answers (5)

Juan J
Juan J

Reputation: 413

I know that the question is asked for JavaScript, but if anyone would like to do it in jQuery then it is pretty simple.

You can give your a tag an id and reference it in jQuery to do a certain action.

All you need to do, - to avoid the scroll to top is to disable the default action of the a tag.

Code:

$( "#a-tag-id" ).click(function(e) {
        e.preventDefault();
        alert( "Hello World" );
    });

Upvotes: 1

David Hedlund
David Hedlund

Reputation: 129782

The trick is that your onclick returns the value of somefunction, so that if you make sure somefunction always return false, then the event will return false as well, and cancel the default behavior of the anchor.

So this should solve your problem:

somefunction = function () { alert('foo'); return false; }

But I should mention that when there is an error somewhere in somefunction, the rest of the javascript will not execute, and the browser will still follow the link to #. It is advisable, therefore, to use javascript:void(0) instead, as this will rid you of that problem.

Upvotes: 5

jamesdlin
jamesdlin

Reputation: 89926

You need to make somefunction() return false, or you need to explicitly add return false to your onclick handler. For example:

<a href="#" onclick="somefunction(); return false;">anchor</a>

This will have the browser ignore the href portion of the link when someone clicks on it.

Upvotes: 2

ZoogieZork
ZoogieZork

Reputation: 11279

Return false from your onclick handler, e.g.:

<a href="#" onclick="somefunction(); return false;">anchor</a>

Upvotes: 2

Oded
Oded

Reputation: 498904

The onclick causes the page to resubmit, therefore scrolling to the top.

You need the onclick event to return a false in order to avoid the postback.

This can be done by changing your function to return a false:

somefunction = function () {alert('foo'); return false;}

Or to change the link and onClick event to do so:

<a href="javascript:void(0)" onclick="somefunction(); return false;">anchor</a>

Upvotes: 57

Related Questions