Including both href and onclick to HTML <a> tag
To trigger JavaScript without navigating away on an <a> tag click, combine href with an onclick event and halt the default action. Use event.preventDefault() within the onclick function or return false directly in the onclick attribute. Example:
This ensures the link's default behavior (navigation) is suppressed, and only your JavaScript function runs.
Best practices: managing onclick and href
The golden rule: Keep JavaScript out of HTML
In-line JavaScript, while convenient, is often frowned upon due to its disorganization. Instead, you can bind a click event listener to your <a> tag using document.querySelector or document.getElementById for more readability and maintainability:
Walking the semantics tightrope: choosing between <a> and <button>
Consider using a <button> when the click action doesn't lead to navigation. Style your button to look like a link for a seamless user experience:
Your stylesheet becomes a costume designer, dressing button as a pseudo-<a> tag.
Manual navigation: commandeer href after onclick
You can prioritize onclick over href, but still take a scenic route to href after onclick by manipulating window.location:
Now, you're the captain piloting the navigation after your custom logic!
The jQuery shortcut
Using jQuery, managing click events becomes a piece of cake. 🍰
jQuery is indeed the Swiss Army Knife of JavaScript, simplifying event management significantly.
For all occasions: dealing with edge cases
Resolving the mystery of "#"
Implement href="#" as a placeholder cautiously as it may teleport the user to the top of the page. It's the elevator's "Open door" button of the web. Remember to prevent its default action:
Accessibility first: empty hrefs
Links with a void href like href="#" or href="javascript:void(0)" can perplex assistive technologies and users alike. Use button for non-navigating actions to promote accessibility.
The evolution of <a>: staying in the loop
Brush up on the best practices on <a> elements and onClick events by bookmarking resources like MDN. Staying informed ensures your HTML navigates smoothly with the changing tides.
Was this article helpful?