[javascript] 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.

This question is related to javascript html onclick anchor href

The answer is


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.


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;
}

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();
}

    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>

<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


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">

Try using javascript:void(0) as follows-

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


You can use this simple code:

<a href="" onclick="return false;">add new action</a><br>

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();
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to onclick

How to use onClick with divs in React.js React prevent event bubbling in nested components on click React onClick function fires on render Run php function on button click Passing string parameter in JavaScript function Simple if else onclick then do? How to call a php script/function on a html button click Change Button color onClick RecyclerView onClick javascript get x and y coordinates on mouse click

Examples related to anchor

How to open a link in new tab using angular? Attaching click to anchor tag in angular How to create a link to another PHP page Making href (anchor tag) request POST instead of GET? Difference between _self, _top, and _parent in the anchor tag target attribute How can I create a link to a local file on a locally-run web page? How to open link in new tab on html? Getting a link to go to a specific section on another page Pure CSS scroll animation Make anchor link go some pixels above where it's linked to

Examples related to href

File URL "Not allowed to load local resource" in the Internet Browser Angular 2 router no base href set How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Html- how to disable <a href>? Add php variable inside echo statement as href link address? ASP MVC href to a controller/view href="tel:" and mobile numbers How can I disable the bootstrap hover color for links? How can I disable HREF if onclick is executed? Open link in new tab or window