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:
Let fragment be document's URL's fragment.
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.