122

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.

2
  • 4
    I would use to anchors one with an href and one without. On page load check if javascript is enabled, if it is show the correct anchor else show the other.
    – ewein
    Mar 25, 2013 at 18:33
  • 1
    @ewein Why? That sounds like an awful lot of markup for a simple feature.
    – Ky -
    Sep 23, 2015 at 13:53

10 Answers 10

87

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/

4
  • 1
    Over the past couple years I've changed my mind; this is a better solution
    – Ky -
    Oct 12, 2017 at 0:42
  • 1
    How wholesome ! May 16, 2018 at 8:11
  • But this is not working with JSX react. Will this work?
    – Coder
    Oct 10, 2019 at 9:41
  • 2
    this saved a lot of time. Apr 30, 2020 at 8:48
63
    yes_js_login = function() {
         // Your code here
         return false;
    }

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:

<a href="http://example.com/no-js-login" onclick="yes_js_login(); return false;">Link</a>
4
  • 1
    The edited answer does not answer the question, as it removes the actual link. Jan 7, 2014 at 13:34
  • 13
    alternatively use onclick="return yes_js_login();" with yes_js_login returning false Jun 19, 2014 at 8:26
  • 1
    @cgogolin see my answer.
    – Gabe Rogan
    May 3, 2017 at 16:15
  • for anyone who still stuck, may adding this line event.stopImmediatePropagation()
    – didxga
    Jul 31, 2017 at 7:33
51

Simply disable default browser behaviour using preventDefault and pass the event within your HTML.

<a href=/foo onclick= yes_js_login(event)>Lorem ipsum</a>

yes_js_login = function(e) {
  e.preventDefault();
}
1
  • 2
    return false did not work in polymer... above solution did work... Thanks Mar 7, 2018 at 17:38
21

You can use this simple code:

<a href="" onclick="return false;">add new action</a><br>
0
19
<a href="http://www.google.com" class="ignore-click">Test</a>

with jQuery:

<script>
    $(".ignore-click").click(function(){
        return false;
    })
</script>

with JavaScript

<script>
        for (var i = 0; i < document.getElementsByClassName("ignore-click").length; i++) {
            document.getElementsByClassName("ignore-click")[i].addEventListener('click', function (event) {
                event.preventDefault();
                return false;
            });
        }
</script>

You assign class .ignore-click to as many elements you like and clicks on those elements will be ignored

2
  • This is a great solution! I used it for buttons that I have that when clicked a pseudo class .btn-loading is added to the clicked link, then if successful a checkmark(on error an X) replaces the loading animation. I don't want the button to be able to be clicked again in some instances(for both success and error), using this I can simply $(elemnent).addClass('disabled') and easily achieve the functionality I was looking in an elegant way! Feb 21, 2018 at 5:05
  • I don't know why my code does not work? var modal_button = document.querySelectorAll('[href="#bookingform"]'); if(modal_button.length){ for (var i = 0; i < modal_button.length; i++) { modal_button[i].addEventListener('click',function(e){ // some code e.preventDefault(); return false; }); } } Mar 30, 2021 at 7:15
7

It's simpler if you pass an event parameter like this:

<a href="#" onclick="yes_js_login(event);">link</a>
function yes_js_login(e) {
    e.stopImmediatePropagation();
}
2
  • 3
    That doesn't work for me. I have to use e.preventDefault() Dec 6, 2015 at 20:02
  • onclick="event.stopImmediatePropagation();" works for me Aug 24, 2022 at 15:20
6

Try using javascript:void(0) as follows-

<a href="javascript:void(0)" onclick="...">Text</a>

1
  • Thank you for chipping in. This doesn't help the scenario that I posed in my original question: "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."
    – Ky -
    Dec 1, 2020 at 15:57
2

This might help. No JQuery needed

<a href="../some-relative-link/file" 
onclick="this.href = 'https://docs.google.com/viewer?url='+this.href; this.onclick = '';" 
target="_blank">

This code does the following: Pass the relative link to Google Docs Viewer

  1. Get the full link version of the anchor by this.href
  2. open the link the the new window.

So in your case this might work:

<a href="../some-relative-link/file" 
onclick="this.href = 'javascript:'+console.log('something has stopped the link'); " 
target="_blank">
1

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:

<a onclick="http://blahblah" href="http://blahblah" target="_blank">A regular link</a>
<a onclick="javascript:myFunc($(this));return false" href="javascript:myFunc($(this));"  target="_blank">javascript with self reference</a>

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.

3
  • why are there two? Why are you putting JS in the HREF?
    – Ky -
    Aug 19, 2014 at 18:43
  • Supuhstar, The actual code is dynamic, javascript, and will generate an <a> element for several hundred items that are defined externally. Each item will either specify a static link address, and thats where the generated <a> element should use the regular "href behaviour". Or, a javascript function call is specified for the item, in which case the <a> element's behaviour is calculated, based on the element's context. And in the code for the <a> generator, I just wanted to copy whatever is specified for each element, no testing whether it's a link address or a javascript funtion call. Oct 8, 2014 at 11:49
  • I don't understand how this answers my question. Who said I wanted several hundred links? I really don't understand the point of all this, or even half of what you just said.
    – Ky -
    Oct 8, 2014 at 13:23
0

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:

var elementsOtherSection = document.querySelectorAll("#vehicle-item").length;
if (elementsOtherSection> 10){
     return true;
}else{
     event.preventDefault();
     return false;
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.