Html anchor link - href and onclick both?
Combine href
for navigation and onclick
for JavaScript actions within an <a>
tag. Let a function run onclick
and let the function's return value govern navigation: true
enables usual link behavior, false
prevents it. Example:
To abort the navigation after onclick
action:
doSomething()
is a certain JavaScript function that will run before the navigation or abort it. This method ensures usability with JavaScript disabled (fallback to href
).
Interactive navigation with JavaScript
Event handlers are your friends offering a better optimized approach compared to inline JavaScript. They can attach to an `onclick`` event on your link:
Overriding defaults for turbo control
Pause the default action using event.preventDefault()
. It allows your JavaScript to take the wheel, useful when dealing with the dark arts of async operations or dynamic navigation decisions.
Navigating on the wind of JavaScript
Sometimes you want to sail to a URL decided during your onclick
event, window.location.href
is your compass:
Promoting JavaScript to a new home
Think outside the box. (Or should I say, outside the tag?) Consider external scripts
to improve code clarity and separate church from state:
A journey with jQuery
For those of you on the jQuery bandwagon, binding click events is a cinch:
By using jQuery's .click()
, your code can get a makeover, becoming more fabulous and low-maintenance. Just don't forget to invite jQuery to the party:
Inline JS vs External JS: The Ultimate Smackdown
Inline JS | External JS |
---|---|
Quick and dirty | Clean and sustainable |
Maintenance? What maintenance? | Debugging like a boss |
HTML? More like HT-Mess! | An HTML Mona Lisa |
Reign over dynamic links
Even dynamically-created links can sport both href
and onclick
:
For the sake of accessibility, don't forget href
even when conjuring links out of the ether.
Was this article helpful?