How can I prevent a click on a '#' link from jumping to top of page?
Prevent #
links from causing a page jump by disrupting the default behavior with JavaScript.
Implement this JavaScript snippet, and henceforth your #
links will cease to ascend the page.
An alternate universe sans JavaScript
There could be scenarios where JavaScript isn't feasible, in these cases you have a few alternate solutions:
-
Update the href attribute: Switch
href="#"
tohref="#!"
orhref="#/"
. This will not cause the page to jump, which equals zero elevator rides to the top of the document. -
Interchanging to buttons: If your link is an on-page command rather than navigation, consider styling a
<button>
element as a link. It avoids jumping behaviors and doesn't form a new browser-level history record.
Building a wholesome experience for users
Inhibit the default behaviors under consideration of accessibility and user experience:
-
Accessibility matters: Make sure your chosen solution complies with WCAG standards. Using
javascript:void(0);
can interfere with screen readers, and move on to alienating your users reliant on assistive technologies. Employing ARIA roles or creating distinct button actions could provide a far more viable solution. -
Design coherency: Preserving visual consistency throughout your site is critical. Regardless of whether you're using buttons or links, the look and feel should meet users' expectations and should make sense in the larger context.
Become proactive with jQuery
Utilizing jQuery allows you to handle the click events at a much granular level, hence providing superior control:
Ensure testing at throughput to round off legitimacy of navigational links and page interactions.
Harnessing the power of event handling
A key aspect of managing default link behaviors rests in the understanding event propagation. event.stopPropagation()
can be a boon in complex scenarios wherein preventing an event's bubbling up the DOM is essential.
Strategies for different scenarios
Select your tactics base on the situation:
-
Dynamic content: For dynamically added links or updated content, utilize event delegation to ensure every link has the desired behavior, regardless of when it's added.
-
URL manipulation: Use the HTML5 History API to change URLs in the browser without a refresh and without jumps.
history.pushState
orhistory.replaceState
are your friends here. No more awkward jumps to the top of the page! -
Smooth scrolling: Sometimes, you do want to jump to anchors but in a less intrusive manner. Try smooth scrolling either with a CSS
scroll-behavior
property or via a JavaScriptscrollIntoView({behavior: 'smooth'})
method.
Was this article helpful?