271

I'm currently using <a> tags with jQuery to initiate things like click events, etc.

An example of what I'm doing is: <a href="#" class="someclass">Text</a>.

But I dislike how the '#' makes the page jump to the top of the page. What can I do instead?

starball
  • 20,030
  • 7
  • 43
  • 238
st4ck0v3rfl0w
  • 6,665
  • 15
  • 45
  • 48
  • 1
    Duplicate of http://stackoverflow.com/questions/720970/jquery-hyperlinks-href-value/721021#721021 – Bogdan Constantinescu Jul 15 '10 at 06:59
  • 2
    I'm with David Dorward here, and [gargantaun](http://stackoverflow.com/questions/720970/jquery-hyperlinks-href-value/721004#721004) on the linked duplicate question. If you have links on your website, they need to function as normal links. If JavaScript intercepts them and does something different, all well and good, but you need to have a real link there, that leads to a real page. This is necessary for all kinds of reasons, not the least of which are SEO and accessibility. – Daniel Pryden Jul 15 '10 at 07:11
  • *“Stupid is as stupid does”* We've all been there before :) – takeshin Jul 15 '10 at 12:24

25 Answers25

383

So this is old but... just in case someone finds this in a search.

Just use "#/" instead of "#" and the page won't jump.

T J
  • 42,762
  • 13
  • 83
  • 138
Chris
  • 3,955
  • 1
  • 12
  • 2
  • 62
    that works because it navigates to the anchor named `/`, not because `#/` has any meaning. you can do the same thing with `#whateveryouwant` and it will prevent a jump to the top – slang Jun 12 '15 at 15:54
  • 3
    @slang, although you are right, and this is just nitpicking, but I'd prefer to use "#/" instead of "#whateveryouwant" because "#/" is used quite common and thus reveals intentions (Clean Code). It could still be an addition to the answer though. – jobbert May 04 '16 at 11:01
  • Doesn't work if you want to use #mydiv:target {display:block} if the element is hidden on the page you're navigating to. Any suggestions? – Jonathan May 06 '16 at 09:46
  • 30
    Beware - this creates a record in browser history so clicking back will not do what the user thinks it will do after clicking a link with `#/` or anything else e.g. `#whatever`. – StudioTime Sep 05 '16 at 07:36
  • 1
    @DarrenSweeney You are right but just using a # creates a record in browser history too. Basically the behavior is the same. – Gary Brunton Jan 11 '17 at 16:51
  • 1
    does anyone know why jumping happens in the first place? – Reuben S May 10 '22 at 12:15
  • @ReubenS see [my answer](https://stackoverflow.com/a/75839594/11107541). TL;DR: because the HTML spec says so. – starball Mar 25 '23 at 04:07
  • This worked for me! I had never thought to use this and appreciate you sharing it. – Murray Chapman Apr 24 '23 at 00:52
278

In jQuery, when you handle the click event, return false to stop the link from responding the usual way prevent the default action, which is to visit the href attribute, from taking place (per PoweRoy's comment and Erik's answer):

$('a.someclass').click(function(e)
{
    // Special stuff to do when this link is clicked...

    // Cancel the default action
    e.preventDefault();
});
Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 1
    @pranay: OP specified that he's using jQuery to work with these links. – BoltClock Jul 15 '10 at 05:40
  • 10
    Instead of return false, do an event.preventDefault(). This is more clear for the people who will read your code. – RvdK Jul 15 '10 at 06:06
  • @PoweRoy: got it. I made the edit and learned something new :) – BoltClock Jul 15 '10 at 06:24
  • 5
    @BoltClock The OP should use buttons to handle the click events instead of anchors. Your answer is pretty useful, but in the case when href points somewhere and you don't need the redirect *at the moment*. Preventing default behavior of action not needed at all is a kind of advice like: take the knife, grab the blade and hammer the nails using the handle :) Take a right tool for the job! – takeshin Jul 15 '10 at 07:14
  • 2
    If jquery: `$('a[href=#]').click(function(e) { e.preventDefault(); });` – Snufkin May 05 '18 at 10:40
71

you can even write it just like this:

<a href="javascript:void(0);"></a>

im not sure its a better way but it is a way :)

guy schaller
  • 4,710
  • 4
  • 32
  • 54
  • This method was fine for pre-HTML 4 but today it is very bad practice as it breaks too many navigation actions such as "open link in new tab". – Steve-o Jul 15 '10 at 07:20
  • 7
    you are maybe right but.. in this case it dosnt matter because he is giving an onclick event so open link in new tab wouldnt work anyway... – guy schaller Jul 15 '10 at 08:48
  • Shortcut is `href='javascript:;'` but be careful it triggers window.beforeUnload event in IE – Mihir May 20 '16 at 07:22
  • This might break his own function? Because if I do this my func to render slides is no longer triggerd. – user3806549 Sep 13 '16 at 09:47
59

Solution #1: (plain)

<a href="#!" class="someclass">Text</a>

Solution #2: (needed javascript)

<a href="javascript:void(0);" class="someclass">Text</a>

Solution #3: (needed jQuery)

<a href="#" class="someclass">Text</a>
<script>
$('a.someclass').click(function(e) {
    e.preventDefault();
});
</script>
Nabi K.A.Z.
  • 9,887
  • 6
  • 59
  • 81
  • 1
    Couldn't you do `$('a[href="#"]')` instead and avoid the use of `someclass`? – ADTC Feb 18 '21 at 03:41
  • 1
    @ADTC If we want to apply to all tags, this is a very good solution. But my answer was in line with the question that had been asked and had to be applied to a specific tag. – Nabi K.A.Z. May 03 '21 at 02:48
  • The question isn't clear then. I read it as the asker wanting to apply it on all of them, and the `someclass` just happened to be there in code by chance. As it says: _"I hate how the '#' makes the page jump to the top of the page. What can I do instead?"_ sounded to me like he wants it globally changed. ‍♂️ (When it's not clear if it's one or the other, I'd just mention both cases in the answer. After all, it's not only the asker who reads your answer but thousands of other visitors searching for a solution to a similar problem. ) – ADTC May 04 '21 at 04:12
  • @ADTC The focus in stackoverflow is on the exactly question. But anyway anyone know for specific html tag or all html tag what can do it. – Nabi K.A.Z. May 04 '21 at 17:16
  • a shorter version of `href="javascript:void(0);"` is `href="javascript:;"` – Alex from Jitbit Jul 21 '21 at 16:32
17

You can use event.preventDefault() to avoid this. Read more here: http://api.jquery.com/event.preventDefault/.

12

Just use <input type="button" /> instead of <a> and use CSS to style it to look like a link if you wish.

Buttons are made specifically for clicking, and they don't need any href attributes.

The best way is to use onload action to create the button and append it where you need via javascript, so with javascript disabled, they will not show at all and do not confuse the user.

When you use href="#" you get tons of different links pointing to the same location, which won't work when the agent does not support JavaScript.

takeshin
  • 49,108
  • 32
  • 120
  • 164
9

If you want to use a anchor you can use http://api.jquery.com/event.preventDefault/ like the other answers suggested.

You can also use any other element like a span and attach the click event to that.

$("span.clickable").click(function(){
alert('Yeah I was clicked');
});
Neothor
  • 753
  • 1
  • 5
  • 10
7
$('a[href="#"]').click(function(e) {e.preventDefault(); });
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
Praveen Manne
  • 71
  • 1
  • 1
  • 3
    Could you please add a short explanation? – J Fabian Meier Jun 27 '16 at 10:52
  • It looks to me like he's adding a click handler on any anchor that has an href of "#" associated with it. This way, you wouldn't have to search for all the click handlers you already have in place and add e.preventDefault() within them. – Mani5556 Dec 20 '16 at 19:59
7

You can use #0 as href, since 0 isn't allowed as an id, the page won't jump.

<a href="#0" class="someclass">Text</a>
Veve
  • 6,643
  • 5
  • 39
  • 58
  • This is the same as using `#/` and hence has the same problem: Adds to browser history. – ADTC Feb 18 '21 at 03:44
  • @ADTC the question doesn't include anything about browser history. – Veve Feb 18 '21 at 07:33
  • "_since 0 isn't allowed as an id_" says who? https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id – starball Aug 29 '23 at 03:54
6

There are 4 similar ways to prevent the page from jumping to the top without any JavaScript:

Option 1:

<a href="#0">Link</a>

Option 2:

<a href="#!">Link</a>

Option 3:

<a href="#/">Link</a>

Option 4 (Not recommended):

<a href="javascript:void(0);">Link</a>

But it's better to use event.preventDefault() if you are handing the click event in jQuery.

Exil
  • 311
  • 2
  • 11
  • 26
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – A. Suliman Aug 12 '18 at 05:55
4

Links with href="#" should almost always be replaced with a button element:

<button class="someclass">Text</button>

Using links with href="#" is also an accessibility concern as these links will be visible to screen readers, which will read out "Link - Text" but if the user clicks it won't go anywhere.

martinedwards
  • 5,577
  • 1
  • 33
  • 35
4

If the element doesn't have a meaningful href value, then it isn't really a link, so why not use some other element instead?

As suggested by Neothor, a span is just as appropriate and, if styled correctly, will be visibly obvious as an item that can be clicked on. You could even attach an hover event, to make the elemnt 'light up' as the user's mouse moves over it.

However, having said this, you may want to rethink the design of your site so that it functions without javascript, but is enhanced by javascript when it is available.

belugabob
  • 4,302
  • 22
  • 22
3

Just use

<a href="javascript:;" class="someclass">Text</a>

JQUERY

$('.someclass').click(function(e) { alert("action here"); }
Ayush
  • 49
  • 1
3

You could just pass an anchor tag without an href property, and use jQuery to do the required action:

<a class="foo">bar</a>

kingjeffrey
  • 14,894
  • 6
  • 42
  • 47
3

The #/ trick works, but adds a history event to the browser. So, clicking back doesn't work as the user may want/expect it to.

$('body').on('click', 'a[href="#"]', function(e) {e.preventDefault() }); is the way I went, as it works for already existing content, and any elements added to the DOM after load.

Specifically, I needed to do this in a bootstrap dropdown-menu inside of a .btn-group(Reference), so I did:

$('body').on('click', '.dropdown-menu li a[href="#"]', function(e) {e.preventDefault() });

This way it was targeted, and didn't affect anything thing else on the page.

David
  • 2,094
  • 3
  • 30
  • 47
  • **Unfortunately this is wrong. Don't use this code.** If the first argument of `click` is not a handler, it's event data. It doesn't actually select the `a` tags as expected. The end result? Everything on your page is disabled! – ADTC Feb 18 '21 at 04:19
2

I have used:

<a href="javascript://nop/" class="someClass">Text</a>
Brice Roncace
  • 10,110
  • 9
  • 60
  • 69
2

To prevent the page from jumping, you need to call e.stopPropagation(); after calling e.preventDefault();:

stopPropagation prevents the event from going up the DOM tree. More info here: https://api.jquery.com/event.stoppropagation/

  • could you please provide the full code that I could pasted in my html ? I'm using Zurb Foundation 5.5.3. – Julie S. Jun 17 '16 at 20:49
2

I've always used:

<a href="#?">Some text</a>

when trying to prevent the page jump. Not sure if this is the best, but it seems to have been working well for years.

Josh Harris
  • 446
  • 4
  • 8
1

You can also return false after processing your jquery.

Eg.

$(".clickableAnchor").live(
    "click",
    function(){
        //your code
        return false; //<- prevents redirect to href address
    }
);
1

I use something like this:

<a href="#null" class="someclass">Text</a>
stefan
  • 2,685
  • 2
  • 24
  • 31
1

If you want to migrate to an Anchor Section on the same page without page jumping up use:

Just use "#/" instead of "#" e.g

<a href="#/home">Home</a>
<a href="#/about">About</a>
<a href="#/contact">contact</a> page will not jump up on click..
0

Adding something after # sets the focus of page to the element with that ID. Simplest solution is to use #/ even if you are using jQuery. However if you are handling the event in jQuery, event.preventDefault() is the way to go.

Exil
  • 311
  • 2
  • 11
  • 26
0

The <a href="#!">Link</a> and <a href="#/">Link</a> does not work if one has to click on the same input more than once.. it only takes in 1 event click for each on multiple inputs.

still the best way to go is with <a href="#">Link</a>

then,

event.preventDefault();
Richard Rosario
  • 115
  • 1
  • 12
0

The simplest one for me was to do this.

<a href="#" onclick="return false;">Some text</a>

The reason for using JS is that most modern sites rely on it.

FiddlingAway
  • 1,598
  • 3
  • 14
  • 30
0

If you don't have a semantic reason to use an anchor element- such as seems to be the case here where you (if I understand correctly) don't want to link to anything- then you should check to see if there is a more semantically appropriate element. Perhaps that might be a button element.


If you insist on using an anchor element and actually just don't want there to be an href attribute at all,... just don't add one. See also: Is an anchor tag without the href attribute safe?. It's valid in HTML5 to have an anchor tag with no href. See https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-a-element, which states:

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.


If you insist on putting # as the href, you can prevent scrolling to the top of the page with Event.prototype.preventDefault in an event listener, which you can add with EventTarget.prototype.addEventlListener or jQuery's .click() method. If you have issues with needing to get the event listener to be called earlier than other ones which are already registered, then you can try specifying you listener to listen for the event during the capturing phase with the useCapture (third) parameter, or the capture field if you use the options object signature of addEventListner.

$('<your selector goes here>').click(function(ev) {
    ev.preventDefault();
});

The reason why this works and the reason why the scroll-to-top happens in the first place is because that's what the HTML spec specifies is supposed to happen. See https://html.spec.whatwg.org/multipage/browsing-the-web.html#scrolling-to-a-fragment, which states:

For an HTML document document, the following processing model must be followed to determine its indicated part:

  1. Let fragment be document's URL's fragment.

  2. If fragment is the empty string, then return the special value top of the document.

[...]

Bonus info: If you read on, you'll also see that if you set the href to #top, that is also specified to cause scrolling to the top to happen.

starball
  • 20,030
  • 7
  • 43
  • 238