4

So, I'm working on a site at the moment that has a jquery onClick function. Well, the link is a simple href="#".

Well, every time it is clicked,

  1. The # sign appends to the URL
  2. The site navigates to the top of the page

Is there a better alternative, or am I doing something wrong?

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
PaulHanak
  • 729
  • 2
  • 9
  • 21

5 Answers5

7

In your click handler, add return false;.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
3

Your onclick function needs have a return false in it. Or you can do this :

<a href="#" onclick="doSomething();return false;">click</a>
Mike Park
  • 10,845
  • 2
  • 34
  • 50
2

I use this as an alternative

<a href="javascript:void(0)" onclick="doSomething();return false;">click</a>
1

A little bit late, but if you're using jQuery, in your event handler you can use

$("#myButton").on("click", function(e)
{
    // Whatever the button should do

    e.preventDefault();
});

The e.preventDefault() does exactly that, it prevents the default behaviour, that would be to scroll to the top of the page (which is what the # symbol represents on its own).

José Tomás Tocino
  • 9,873
  • 5
  • 44
  • 78
0

The hash follow by an id is a link to an anchor tag with said id. If the anchor tag doesn't exist, it certainly could explain why it's hitting the top of the page.

OnResolve
  • 4,016
  • 3
  • 28
  • 50