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.
If you return false it should prevent the default action (going to the href).
Edit: Sorry that doesn't seem to work, you can do the following instead:
This might help. No JQuery needed
This code does the following: Pass the relative link to Google Docs Viewer
this.href
So in your case this might work:
You can use the first un-edited solution, if you put return first in the
onclick
attribute:Example: https://jsfiddle.net/FXkgV/289/
In my case, I had a condition when the user click the "a" element. The condition was:
If other section had more than ten items, then the user should be not redirected to other page.
If other section had less than ten items, then the user should be redirected to other page.
The functionality of the "a" elements depends of the other component. The code within click event is the follow:
This worked for me:
with jQuery:
with JavaScript
You assign class
.ignore-click
to as many elements you like and clicks on those elements will be ignored