133

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>';
3
  • in some conditions i want this tag to be completely disabled: What does this mean? What conditions? Commented Mar 21, 2011 at 10:41
  • 1
    By disabled you mean you want the text to still appear as link (underline and everything) but do nothing when clicked? Commented Mar 21, 2011 at 10:47
  • Possible duplicate of How do you make an anchor link non-clickable or disabled? Commented Apr 18, 2016 at 8:16

21 Answers 21

217

Try this when you dont want user to redirect on click

<a href="javascript: void(0)">I am a useless link</a>
Sign up to request clarification or add additional context in comments.

9 Comments

How about <a href='javascript:;'>I am a shorter useless link</a>?
Don't even need the semicolon.
You web developers put millions of tabs\t, line feeds\n and spaces to just see the code folded and nice(for who? browser) and now are worrying about 7 bytes void(0) and/or a ;, o god.
I slightly disagree with the above comment. Sometimes things need to be descriptive and in other cases to be simpler and easier to remember. I would prefer "javascript:".
In my opinion - Millions millions of tabs\t, line feeds\n and spaces - yep, this make code easy to understand, while void(0) is not. Thats why this should be removed or must be as short as possible. E.g. here shorter - is for understanding (reading) not for "compression" or bytes ecomony. :)
|
97

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

9 Comments

Must thank you for the pointer-events:none; I never knew about that tag, came in very handy!
This is fantastic, but it's worth noting that pointer-events is not supported in IE before version 11. caniuse.com/#feat=pointer-events
I tried it out on this page by editing the global styles but then I couldn't upvote you :)
This is bad for accessablity. It only covers mouse interaction. Keyboard interactions still work normally. Anyone with a screen reader will have no idea the link is supposed to be "disabled".
@DanielMorell Agreed. w3.org/TR/html-aria/… suggests setting aria-disabled="true" ("If an author were to specify an aria-disabled=true on an HTML hyperlink […]"). However, then the link still remains tab-and-enter-able for regular users, so some additional JavaScript event handler logic is needed, e.g. onclick="event.preventDefault()".
|
15

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

5 Comments

# is not recommended, why? consider this, your disabled link appears in bottom/footer of a lengthy page, clicking the link will take you to top, "javascript:;" is enough
#1 won't scroll back to the top
@Bixi, it will scroll to an element with an id of 1 if one gets added later.
Well yeah it's obvious. Knowing that just never create an id=1. It's just a possible workaround
This will not work if you have a <base> different than your current page
14

Try this using jQuery:

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

Comments

13

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

3 Comments

This is the best answer I've seen for disabling <a> elements. I was a looking for a progressive enhancement approach which enabled the links to work normally for users with javascript turned off but disable the links and enhance them when javascript was available. Removing the attribute (and optionally storing the value in data-href) works very well when using unobtrusive javascript.
I agree with what you said. On top of that you can also add element.style.cursor = "not-allowed"; element.style.background= "#6c757d"; to make it look like it is disabled too.
Great solution because you can simply set a CSS like a:not([href]) { color: #ccc; } and automatically get the link to visually change too, no javascript needed!
6

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

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

2 Comments

By adding true as a third argument (useCapture) for addEventListener it also overrides onclick=.
Use of a return value is no longer recommended: developer.mozilla.org/en-US/docs/Web/API/Event/returnValue
5
(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

2 Comments

Is unbind necessary? I believe return false or e.preventDefault() would suffice.
Please explain what is wrong with OP's code and why this solves the problem by editing your answer.
5

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>

Comments

4

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.

Comments

4
anchor.href = null;

1 Comment

chrome tries to navigate to a page named null for this answer now
3

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

2 Comments

Can you put an example please? Some browsers "jump" is true.. :)
Good to see you, @ArupRakshit =) The accepted answer does it with javascript: void(0); or javascript:; . If you're rendering from Rails, just render a span instead where you want it disabled.
3

This is possible, too:

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

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

1 Comment

please review existing answer
3

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>

Comments

2

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

Comments

1

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.

Comments

1

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

2 Comments

someone needed to put it as an answer, bootstrap people have done it for a reason. Even if it is a bad idea, it is still an answer and with explanation why the idea is bad the answer is brings good to people.
answer improved
0

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

Comments

0

Instead of void you can also use:

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

Comments

0

The easiest way is just element.style.pointerEvents = "none";

Someone mentioned something a bit similar above, but no need for any custom CSS - just set the style property directly in your JS and then back to "" when/if you want to re-enable it later.

Comments

0

I was able to disable using className attribute of href like this

let hrefClass = "btn btn-primary"
if (items.length == 0) {
    hrefClass = "btn btn-primary disabled"
}
let url = `\api\bills\csv?${items.join(',')}`
<a href={ url } className={hrefClass} target="_blank" rel="noopener noreferrer" >

Comments

-2
 <a href="https://" onclick="MyFunction();return false;">

1 Comment

Why do it this way? Can you edit and explain?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.