I have numerous anchor tags on my page that only trigger jQuery actions on the same page.
The don't redirect the user to another location, which is the normal expected behavior of an anchor tag.
I don't want to have restful urls in my app for every action. But, I also don't like sending the user to the top of the page every time they click on one of these <a href="#">
tags.
What's a better value to put inside the href
value of the anchor tag besides #
?
You should really be using a
<button>
element for JS-only actions. They have a default action (if inside a form) but outside of a form they’re purely for user triggered actions that you bind your JS event handler to.Use this to stop browser sending them to top of page?
Can you reference a fragment on the page that could work as a logical fallback to the non-executed JavaScript action? If so, it makes a lot of sense to reference
<a href="#account">
and have anid="account"
on the page that could work as a fallback.Another option is to reference the dynamically loaded content directly; that way you can quite conveniently use the
href
in the Ajax call instead of hard-coding what to request in JavaScript somehow;<a href="/path/to/dynamic/content">
.Lastly, you can not have the
<a href="#">
statically in the HTML at all, but instead create it on the fly with jQuery since it's only used by jQuery anyway. No need to pollute the markup with placeholders for JavaScript if the placeholders are only used by and for JavaScript anyway.Regarding "sending the user to the top of the page"; you should just
return false
from your the function you have hooked up as aclick()
handler;If the anchor is useless to people who don't have javascript, then they shouldn't see it at all.
The best alternative is to generate these links using jQuery on page load - that way the only people who see them are those who will use them.
In this case, having
href="#"
is fine, because as long as your event handler finishes withreturn false;
then thehref
will never be followedIf you have links that aren't links, perhaps they shouldn't be links? :-) You might consider a different UI element that doesn't have a default behavior (outside of a form), like
button
(you can style buttons to a substantial degree). Or you could usespan
or similar, but if you do be sure to set the appropriate accessibility information (such as an ARIArole="link"
) so that you don't mess up screen readers (and browser tabbing).But if you want to continue to use
<a href="#">...</a>
, just attach a handler to them that callsevent.preventDefault();
or returnsfalse
.