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.
I solved a situation where I needed a template for the element that would handle alternatively a regular URL or a javascript call, where the js function needs a reference to the calling element. In javascript, "this" works as a self reference only in the context of a form element, e.g., a button. I didn't want a button, just the apperance of a regular link.
Examples:
The href and onClick attributes have the same values, exept I append "return false" on onClick when it's a javascript call. Having "return false" in the called function did not work.
You can use this simple code:
Simply disable default browser behaviour using
preventDefault
and pass theevent
within your HTML.<a href=/foo onclick= yes_js_login(event)>Lorem ipsum</a>
It's simpler if you pass an event parameter like this: