I have an anchor with both HREF
and ONCLICK
attributes set. If clicked and Javascript is enabled, I want it to only execute ONCLICK
and ignore HREF
. Likewise, if Javascript is disabled or unsupported, I want it to follow the HREF
URL and ignore ONCLICK
. Below is an example of what I'm doing, which would execute the JS and follow the link concurrently (usually the JS is executed and then the page changes):
<A HREF="http://example.com/no-js-login" ONCLICK="yes_js_login()">Log in</A>
what's the best way to do this?
I'm hoping for a Javascript answer, but I'll accept any method as long as it works, especially if this can be done with PHP. I've read "a href link executes and redirects page before javascript onclick function is able to finish" already, but it only delays HREF
, but doesn't completely disable it. I'm also looking for something much simpler.
How to make this a tag working with href and onClick? The default behavior of the <a> tag's onclick and href properties are to execute the onclick , then follow the href as long as the onclick doesn't return false , canceling the event (or the event hasn't been prevented).
To prevent an anchor from visiting the specified href, you can call the Event interface's preventDefault() method on the anchor's click handle.
onclick does trigger first, the href only goes once onclick has returned!
You can use the first un-edited solution, if you put return first in the onclick
attribute:
<a href="https://example.com/no-js-login" onclick="return yes_js_login();">Log in</a> yes_js_login = function() { // Your code here return false; }
Example: https://jsfiddle.net/FXkgV/289/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With