1

I want to know if it's possible to disable links using this :

<a id="link" href=""></a>
$("#link").attr("disabled", false)

This works with buttons, but not with <a> tags.

I know that it's possible to do :

$('#link').click(function(e) {
    e.preventDefault();
});

Or to even remove the hrefcompletely but using my system this doesn't work, and removing the href will cause serious issues.

So the question is, is there a way to just disable the tag, meaning to make it not clickable/active and to re-activate it as we would do .attr("disabled", false) for buttons?

Mamun
  • 66,969
  • 9
  • 47
  • 59
  • You can't disable hyperlinks by the attribute `disabled`. You can use `disable` attribute only for Form elements like `buttons`,`textboxes` & Etc.. – BadPiggie Jan 07 '19 at 08:36
  • Possible duplicate of [How to disable HTML links](https://stackoverflow.com/questions/10276133/how-to-disable-html-links) – Umair Anwaar Jan 07 '19 at 08:37
  • @BanujanBalendrakumar yep thanks! But I'm looking for a workaround of something to have the same effect :) –  Jan 07 '19 at 08:38

2 Answers2

5

You can use CSS to set pointer-events to none:

$('#remove').click(function(){
  $('#link').css({'pointer-events': 'auto', 'text-decoration': 'underline'});
});
#link{
  pointer-events: none;
  text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="link" href="https://stackoverflow.com/">Stackoverflow</a>

<button id="remove">Enable Link</button>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • And what's the default value to make it work once again? Could you add that to the answer please? :) (Also with jquery if possible, for a complete answer, otherwise thank you this is great!) –  Jan 07 '19 at 08:39
  • A quick google search will tell you the default value to make it work again: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events – Osakr Jan 07 '19 at 08:45
  • @Osakr I know it will, as I said it's just to make the answer more complete, not cuz I couldn't find how to do it. –  Jan 07 '19 at 08:48
0

You may use pointer-events for this.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
<script type="text/javascript">
function toggle() {
    var link = document.getElementById("link");
    link.setAttribute("disabled", link.getAttribute("disabled") != "true");
}
</script>

<style type="text/css">
a[disabled="true"] {
    color: lightgray;
    text-decoration: line-through;
    pointer-events: none;
}
</style>

</head>
<body>
    <a id="link" href="http://stackoverflow.com">Link</a>
    <button onclick="toggle()">Disable/Enable</button>
</body>
</html>
kirschkern
  • 1,197
  • 10
  • 27