Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable HREF if onclick is executed?

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.

like image 238
Ky. Avatar asked Mar 25 '13 18:03

Ky.


People also ask

Can you have onclick and href?

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).

How could you prevent a click on an anchor from going to the link?

To prevent an anchor from visiting the specified href, you can call the Event interface's preventDefault() method on the anchor's click handle.

Does Onclick run before href?

onclick does trigger first, the href only goes once onclick has returned!


1 Answers

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/

like image 73
elproduc3r Avatar answered Sep 22 '22 12:09

elproduc3r