Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML anchor link with no scroll or jump

I have various links which all have unique id's that are "pseudo-anchors." I want them to affect the url hash value and the click magic is all handled by some mootools code. However, when I click on the links they scroll to themselves (or to the top in one case). I don't want to scroll anywhere, but also need my javascript to execute and to have the hash value in the url update.

Simulated sample code:

<a href="#button1" id="button1">button 1</a> <a href="#button2" id="button2">button 2</a> <a href="#" id="reset">Home</a> 

So if you were to click on the "button 1" link, the url could be http://example.com/foo.php#button1

Does anyone have any ideas for this? Simply having some javascript return void kills the scrolling but also kills my javascript (though I could probably work around that with an onclick) but more importantly, prevents the hash value in the url to change.

like image 569
Neil Avatar asked Aug 02 '09 02:08

Neil


People also ask

How do I stop anchor links from scrolling behind sticky?

You could add the scroll-padding-top CSS property to an HTML element with a value of 4rem . Now when you click the anchor link, the browser jumps to the anchor section but leaves padding of 4rem at the top, rather than scrolling the anchor point all the way to the top.

What is empty anchor tag?

An empty anchor is either a sign of a link with no anchor text (the entire landing page URL linked on the source URL) or an image link, which would have no anchor text. You can investigate any of your “empty anchor” backlinks by selecting the blue number of backlinks in the next column.


2 Answers

The whole point of an anchor link is to scroll a page to a particular point. So if you don't want that to happen, you need to attach an onclick handler and return false. Even just adding it as an attribute should work:

<a href="#button1" id="button1" onclick="return false">button 1</a> 

A side of effect of the above is that the URL itself won't change, since returning false will cancel the event. So since you want the URL to actually change, you can set the window.location.hash variable to the value that you want (that is the only property of the URL that you can change without the browser forcing a reload). You can probably attach an event handler and call something like window.location.hash = this.id though I'm not sure how mootools handles events.

(Also you need all of the IDs to be unique)

like image 178
Adam Batkin Avatar answered Sep 21 '22 07:09

Adam Batkin


You can use the code below to avoid scrolling:

<a href="javascript:void(0);">linktxt</a> 
like image 34
kip Avatar answered Sep 21 '22 07:09

kip