[javascript] How do I disable a href link in JavaScript?

I have a tag <a href="#"> Previous </a> 1 2 3 4 <a href="#"> Next </a> and in some conditions I want this tag to be completely disabled.

Code from comments (this is how the link is generated)

if (n_index != n_pages) 
    a = a+'<li><a href="#" onclick="javascript:paginateAjaxPage('+(n_index+1) +','+stype+');">></a></li><li><a href="#" onclick="javascript:paginateAjaxPage('+n_pages+','+stype+');" >>></a></li>'; 
else 
    a = a+'<li><a style="cursor: pointer;" onclick="return false;">></a></li><li><a style="cursor: pointer;" onclick="return false" >>></a></li>'; 
a = a+'</ul></div>';

This question is related to javascript html

The answer is


The easiest way to disable a link is simply not to show it. Run this function whenever you want to test if your condition is met to hide the Previous button (replace if (true) with your condition):

var testHideNav = function() {
    var aTags = document.getElementsByTagName('a'),
        atl = aTags.length,
        i;

    for (i = 0; i < atl; i++) {
        if (aTags[i].innerText == "Previous") {
            if (true) { // your condition to disable previous
                aTags[i].style.visibility = "hidden";
            } else {
                aTags[i].style.visibility = "visible";
            }
        } else if (aTags[i].innerText == "Next") {
            if (false) { // your condition to disable next
                aTags[i].style.visibility = "hidden";
            } else {
                aTags[i].style.visibility = "visible";
            }
        }
    }
};

Then run testHideNav() whenever you need to make the check if your condition has changed.


Thank you All...

My issue solved by below code:

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

anchor.href = null;


Try this using jQuery:

$(function () {
    $('a.something').on("click", function (e) {
        e.preventDefault();
    });
});

Based on many answers and my experience here my best solution:

<a href="javascript:">I am a useless link</a>

Some options and theirs caveats:

<a href="#">I will make you page jump to top</a> 

<a href="#" onclick="DoSomething(); return false;">I'll break others scripts events</a>

<a href="javascript: openPage()" >Please... I should be an onclick event...</a>

<a href="javascript:" onclick="openPage()" >Please...do I even need to be an anchor?</a>

<script>element.removeAttribute("href") // some browsers will remove link style</script>

<script>element.href = null // some browsers will remove link style</script>

<style>
 a.my-off-class {
    pointer-events: none
 }
 /** I disable hover event too. And... Is this a style responsability?
</style>

Install this plugin for jquery and use it

http://plugins.jquery.com/project/jqueryenabledisable

It allows you to disable/enable pretty much any field in the page.

If you want to open a page on some condition write a java script function and call it from href. If the condition satisfied you open page otherwise just do nothing.

code looks like this:

<a href="javascript: openPage()" >Click here</a>

and function:
function openPage()
{
if(some conditon)
opener.document.location = "http://www.google.com";
}
}

You can also put the link in a div and set the display property of the Style attribute to none. this will hide the div. For eg.,

<div id="divid" style="display:none">
<a href="Hiding Link" />
</div>

This will hide the link. Use a button or an image to make this div visible now by calling this function in onclick as:

<a href="Visible Link" onclick="showDiv()">

and write the js code as:

function showDiv(){
document.getElememtById("divid").style.display="block";
}

You can also put an id tag to the html tag, so it would be

<a id="myATag" href="whatever"></a>

And get this id on your javascript by using

document.getElementById("myATag").value="#"; 

One of this must work for sure haha


Use all three of the following: Event.preventDefault();, Event.stopPropagation();, and return false;. Each explained...

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. (Source: MDN Webdocs.)

  • Event.stopPropagation(); : To stop the event from clicking a link within the containing parent's DOM (i.e., if two links overlapped visually in the UI).

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. (Source: MDN Webdocs.)

  • return false; : To indicate to the onevent handler that we are cancelling the link-clicking behavior.

The return value from the handler determines if the event is canceled. (Source: MDN Webdocs.)

Full Working JSBin Demo.

StackOverflow Demo...

_x000D_
_x000D_
document.getElementById('my-link').addEventListener('click', function(e) {
  console.log('Click happened for: ' + e.target.id);
  e.preventDefault();
  e.stopPropagation();
  return false;
});
_x000D_
<a href="https://www.wikipedia.com/" id="my-link" target="_blank">Link</a>
_x000D_
_x000D_
_x000D_


(function ($) {
    $( window ).load(function() {
        $('.navbar a').unbind('click');
        $('.navbar a').click(function () {
            //DO SOMETHING
            return false;
        });
    });
})(jQuery);

I find this way easier to implement. And it has the advantage that you js. Is not inside your html but in a different file. I think that without the unbind. Both events are still active. Not sure. But in a way you only need this one event


Another method to disable link

element.removeAttribute('href');

anchor tag without href would react as disabled/plain text

<a> w/o href </a>

instead of <a href="#"> with href </a>

see jsFiddel

hope this is heplful.


Instead of void you can also use:

<a href="javascript:;">this link is disabled</a> 

you can deactivate all links in a page with this style class:

a {
    pointer-events:none;
}

now of course the trick is deactivate the links only when you need to, this is how to do it:

use an empty A class, like this:

a {}

then when you want to deactivate the links, do this:

    GetStyleClass('a').pointerEvents = "none"

    function GetStyleClass(className)
    {
       for (var i=0; i< document.styleSheets.length; i++) {
          var styleSheet = document.styleSheets[i]

          var rules = styleSheet.cssRules || styleSheet.rules

          for (var j=0; j<rules.length; j++) {
             var rule = rules[j]

             if (rule.selectorText === className) {
                return(rule.style)
             }
          }
       }

       return 0
    }

NOTE: CSS rule names are transformed to lower case in some browsers, and this code is case sensitive, so better use lower case class names for this

to reactivate links:

GetStyleClass('a').pointerEvents = ""

check this page http://caniuse.com/pointer-events for information about browser compatibility

i think this is the best way to do it, but sadly IE, like always, will not allow it :) i'm posting this anyway, because i think this contains information that can be useful, and because some projects use a know browser, like when you are using web views on mobile devices.

if you just want to deactivate ONE link (i only realize THAT was the question), i would use a function that manualy sets the url of the current page, or not, based on that condition. (like the solution you accepted)

this question was a LOT easier than i thought :)


Below code for disabled links:

<a href="javascript: void(0)">test disabled link</a> 

another very simple solution is:

<a href="#">test disabled link</a>

First solution is efficient.


Use a span and a javascript onclick instead. Some browsers "jump" if you have a link and "#" href.


This is possible, too:

<a href="javascript:void(0)" onclick="myfunction()">

Link doesn't go anywhere by your function will be executed.


You can simply give it an empty hash:

anchor.href = "#";

or if that's not good enough of a "disable", use an event handler:

anchor.href = "javascript:void(0)";

0) you better remember that Some browsers "jump" if you have a link and "#" href. So the best way would be a custom JavaScript

1) If you after the custom JavaScript, here it is:

<a href="#" onclick="DoSomething(); return false;">Link</a>

The "return false" prevents the link from actually being followed.

2) You may consider avoid using following

<a href="javascript:void(0);" onclick="DoSomething();">Link</a>

or

  <a href="javascript:;" onclick="DoSomething();">Link</a>

Because the javascript pseudo-protocol can put the page into a waiting state in some browsers, which can have unexpected consequences. IE6 is known for it. But If you don't care about IE6, and you are testing everything - it may be a good solution.

3) If you already have jQuery and bootstrap in your project, you can look into using them like so:

$('.one-click').on("click", function (e) {
   $( this ).addClass('disabled');
});

where .disabled class coming form bootstrap.

Qupte form bootstrap site (here)

Link functionality caveat

The .disabled class uses pointer-events: none to try to disable the link functionality of s, but that CSS property is not yet standardized. In addition, even in browsers that do support pointer-events: none, keyboard navigation remains unaffected, meaning that sighted keyboard users and users of assistive technologies will still be able to activate these links. So to be safe, add a tabindex="-1" attribute on these links (to prevent them from receiving keyboard focus) and use custom JavaScript to disable their functionality.

and the custom JavaScript was shown in section 1


So the above solutions make the link not work, but don't make it visible (AFAICT) that the link is no longer valid. I've got a situation where I've got a series of pages and want to disable (and make it obvious that it's disabled) the link that points to the current page.

So:

window.onload = function() {
    var topics = document.getElementsByClassName("topics");
    for (var i = topics.length-1; i > -1; i-- ) {
        for (var j = topics[i].childNodes.length-1; j > -1; j--) {
             if (topics[i].childNodes[j].nodeType == 1) {
                if (topics[i].childNodes[j].firstChild.attributes[0].nodeValue == this.n_root3) {
                    topics[i].childNodes[j].innerHTML = topics[i].childNodes[j].firstChild.innerHTML;
                }
            }
        }
    }
}

This walks through the list of links, finds the one that points to the current page (the n_root3 might be a local thing, but I imagine document must have something similar), and replaces the link with the link text contents.

HTH


I had a similar need, but my motivation was to prevent the link from being double-clicked. I accomplished it using jQuery:

$(document).ready(function() {
    $("#myLink").on('click', doSubmit);
});

var doSubmit = function() {
    $("#myLink").off('click');
    // do things here
};

The HTML looks like this:

<a href='javascript: void(0);' id="myLink">click here</a>

MDN recommends element.removeAttribute(attrName); over setting the attribute to null (or some other value) when you want to disable it. In this case it would be element.removeAttribute("href");

https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute