Explain Codes LogoExplain Codes Logo

Is an empty href valid?

html
accessibility
best-practices
responsive-design
Anton ShumikhinbyAnton Shumikhin·Oct 30, 2024
TLDR

Yes, an empty href (href="") creates a valid HTML link to the current page. You can use it as a temporary placeholder or to assign JavaScript behaviors without triggering navigation. For interactive links, href="#" combined with event.preventDefault() in JavaScript prevents page scrolling, enhancing usability and convenience.

<!-- Best Placeholder Ever: Just buy me a coffee and I'll show --> <a href="">...</a> <!-- Delivers hot pizza without moving -- Magic? Nah, just JS! --> <a href="#" onclick="event.preventDefault(); orderPizza();">Order<a>

Remember to apply href="#" judiciously to avoid scary UX nightmares. Always endorse accessible, inclusive practices.

Exploring href's deep waters

Empty href attributes do float in the HTML sea, but let's dive into their safe usage, accessibility considerations, and clean coding habits.

Embracing href="javascript:void(0);"

Championing accessibility, the preferred pattern is:

<!-- My kitten's footprint -- Cute, but doesn't take you anywhere --> <a href="javascript:void(0);" onclick="playKittenVideo();">Watch</a>

This code ensures screen readers navigate the buoy and doesn't trigger a page reload or browser history entry.

Making anchors focus-friendly

Anchors float for everyone if they have an href. For anchors minus href, use tabindex and watch them float!

<!-- Floating in the sea of your code --> <a tabindex="0">Hello sailor!</a>

Delving deeper

Let's dive into standards and best practices to deliver a seamless and meaningful user experience.

Compatibility with HTML standards

Empty href are given the green light by both HTML 4.01 and HTML5 standards. Yet, it's considered cleaner to avoid javascript: pseudo-protocol due to potential security and compatibility issues.

The placeholder masterpiece

The href attribute can act as a placeholder, a space for the future interactive element yet to come. This placeholder shouldn't be identified as a hyperlink, installing accurate user expectations.

Interaction with the browser

href can leave marks in browser history and page reloads. While using href="#" can unintentionally design a history maze, href="javascript:void(0);" doesn't scribble on your browser's ancient scroll.

Accessibility checklist for developers

When designing links, here are some golden rules for successful treasure digging:

  • href attribute: Makes it recognizable as a hyperlink.
  • role="button": Defines elements acting as buttons.
  • title attribute: Can provide additional context.
  • tabindex: Ensures keyboard accessibility.
  • JavaScript actions within event handlers: Prevents default behavior.