How do I disable a href link in JavaScript?
Try this when you dont want user to redirect on click
<a href="javascript: void(0)">I am a useless link</a>
Disabled href tag
There is no disabled attribute for hyperlinks. If you don't want something to be linked then you'll need to remove the <a>
tag altogether.
Alternatively you can remove its href
attribute - though this has other UX and Accessibility issues as noted in the comments below so is not recommended.
How to disable or enable href links and change the contents of it?
On the server side, it would be an obvious place to not show a link
EJS
<p class="vocab paragraph inherit-colored info__content info__content-creator">
<% if (creatorUrl) { %>
<a href="<%= creatorUrl %>">Creator Name</a>
<% } else { %>
Creator Name
<% } %>
</p>
On the client side you can do this to replace empty links with their textContent
window.addEventListener("load",function() { [...document.querySelectorAll(".info__content-creator a[href^='#']")].forEach(lnk => lnk.parentNode.replaceChild(document.createTextNode(lnk.textContent), lnk));})
<p class="vocab paragraph inherit-colored info__content info__content-creator"> <a href="#">Creator Name</a></p>
<p class="vocab paragraph inherit-colored info__content info__content-creator"> <a href="createorpage.html">Creator Name</a></p>
How can I disable HREF if onclick is executed?
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/
Disable href of HTML using javascript
I think you can do something like: jsFiddle
HTML:
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>Button</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mr.XX</td>
<td>
<input id="ageInput" type="text" value="20" />
</td>
<td>Street XX</td>
<td><a name="sendName" id="sendId" href="#">Clik Here</a>
</td>
</tr>
</tbody>
</table>
JS:
$(document).ready(function () {
$('#ageInput').keyup(function (e) {
var age = $(this).val();
if (age != 20) {
// anything what should happend if its not 20 f.e.:
$('#sendId').hide();
} else {
// anything what should happend if it is 20 f.e.:
$('#sendId').show();
}
});
});
How to disable HTML links
You can't disable a link (in a portable way). You can use one of these techniques (each one with its own benefits and disadvantages).
CSS way
This should be the right way (but see later) to do it when most of browsers will support it:
a.disabled {
pointer-events: none;
}
It's what, for example, Bootstrap 3.x does. Currently (2016) it's well supported only by Chrome, FireFox and Opera (19+). Internet Explorer started to support this from version 11 but not for links however it's available in an outer element like:
span.disable-links {
pointer-events: none;
}
With:
<span class="disable-links"><a href="#">...</a></span>
Workaround
We, probably, need to define a CSS class for pointer-events: none
but what if we reuse the disabled
attribute instead of a CSS class? Strictly speaking disabled
is not supported for <a>
but browsers won't complain for unknown attributes. Using the disabled
attribute IE will ignore pointer-events
but it will honor IE specific disabled
attribute; other CSS compliant browsers will ignore unknown disabled
attribute and honor pointer-events
. Easier to write than to explain:
a[disabled] {
pointer-events: none;
}
Another option for IE 11 is to set display
of link elements to block
or inline-block
:
<a style="pointer-events: none; display: inline-block;" href="#">...</a>
Note that this may be a portable solution if you need to support IE (and you can change your HTML) but...
All this said please note that pointer-events
disables only...pointer events. Links will still be navigable through keyboard then you also need to apply one of the other techniques described here.
Focus
In conjunction with above described CSS technique you may use tabindex
in a non-standard way to prevent an element to be focused:
<a href="#" disabled tabindex="-1">...</a>
I never checked its compatibility with many browsers then you may want to test it by yourself before using this. It has the advantage to work without JavaScript. Unfortunately (but obviously) tabindex
cannot be changed from CSS.
Intercept clicks
Use a href
to a JavaScript function, check for the condition (or the disabled attribute itself) and do nothing in case.
$("td > a").on("click", function(event){
if ($(this).is("[disabled]")) {
event.preventDefault();
}
});
To disable links do this:
$("td > a").attr("disabled", "disabled");
To re-enable them:
$("td > a").removeAttr("disabled");
If you want instead of .is("[disabled]")
you may use .attr("disabled") != undefined
(jQuery 1.6+ will always return undefined
when the attribute is not set) but is()
is much more clear (thanks to Dave Stewart for this tip). Please note here I'm using the disabled
attribute in a non-standard way, if you care about this then replace attribute with a class and replace .is("[disabled]")
with .hasClass("disabled")
(adding and removing with addClass()
and removeClass()
).
Zoltán Tamási noted in a comment that "in some cases the click event is already bound to some "real" function (for example using knockoutjs) In that case the event handler ordering can cause some troubles. Hence I implemented disabled links by binding a return false handler to the link's touchstart
, mousedown
and keydown
events. It has some drawbacks (it will prevent touch scrolling started on the link)" but handling keyboard events also has the benefit to prevent keyboard navigation.
Note that if href
isn't cleared it's possible for the user to manually visit that page.
Clear the link
Clear the href
attribute. With this code you do not add an event handler but you change the link itself. Use this code to disable links:
$("td > a").each(function() {
this.data("href", this.attr("href"))
.attr("href", "javascript:void(0)")
.attr("disabled", "disabled");
});
And this one to re-enable them:
$("td > a").each(function() {
this.attr("href", this.data("href")).removeAttr("disabled");
});
Personally I do not like this solution very much (if you do not have to do more with disabled links) but it may be more compatible because of various way to follow a link.
Fake click handler
Add/remove an onclick
function where you return false
, link won't be followed. To disable links:
$("td > a").attr("disabled", "disabled").on("click", function() {
return false;
});
To re-enable them:
$("td > a").removeAttr("disabled").off("click");
I do not think there is a reason to prefer this solution instead of the first one.
Styling
Styling is even more simple, whatever solution you're using to disable the link we did add a disabled
attribute so you can use following CSS rule:
a[disabled] {
color: gray;
}
If you're using a class instead of attribute:
a.disabled {
color: gray;
}
If you're using an UI framework you may see that disabled links aren't styled properly. Bootstrap 3.x, for example, handles this scenario and button is correctly styled both with disabled
attribute and with .disabled
class. If, instead, you're clearing the link (or using one of the others JavaScript techniques) you must also handle styling because an <a>
without href
is still painted as enabled.
Accessible Rich Internet Applications (ARIA)
Do not forget to also include an attribute aria-disabled="true"
together with disabled
attribute/class.
Disabling href link click if {{permission}}
Hyperlinks don't support the disabled
attribute. But you could create a CSS class that essentially does the same thing, like:
.disabled {
cursor: not-allowed;
}
And then apply that class to the element conditionally:
<a ng-class="{disabled: notAllowed}">Link</a>
notAllowed
is the expression that evaluates to true or false depending on if the user has permission or not.
You might also want to add a function that fires if the link is clicked, preventing the default action. You can then and add it to the element using the ng-click
attribute:
<a ng-class="{disabled: notAllowed}" ng-click="stopClick($event)">Link</a>
$scope.stopClick = function($event) {
if ($scope.notAllowed) {
$event.preventDefault();
}
}
Of course, this can easily be disabled by the user since it's client-side. But that's true with any JavaScript.
How do I disable a link with javascript and css?
To stop the link from taking its default action add return false;
to the onclick
event:
<div class="searchoffertext" onclick="searchoffertext_selected('Banana'); return false;"><a href="./search/Banana">Banana</a></div>
It's probably a better idea to put the onclick
directly on the <a>
But an even better approach would be to use unobtrusive JavaScript to attach an event to the link via a selector.
See also: Stackoverflow: When to use onclick in HTML?
How to disable href after one click
I ended up disabling the href after one click using the following javascript function:
function check(link) {
if (link.className != "visited") {
//alert("new");
link.className = "visited";
return true;
}
//alert("old");
return false;
}
Related Topics
Detect Rotation of Android Phone in the Browser with JavaScript
Is It Safe to Store a Jwt in Localstorage with Reactjs
How to Get Jquery to Select Elements with a . (Period) in Their Id
How to Check If a JavaScript Object Is a Dom Object
JavaScript Filter Array Multiple Conditions
Why How to Use a Function Before It's Defined in JavaScript
Request Header Field Access-Control-Allow-Headers Is Not Allowed by Access-Control-Allow-Headers
What Is the Minimum Valid JSON
Get Mouse Wheel Events in Jquery
How to Download a File Using Window.Fetch
What Does the "|" (Single Pipe) Do in JavaScript
Addeventlistener Not Working in IE8
How Does Basic Object/Function Chaining Work in JavaScript
What Does ':' (Colon) Do in JavaScript
How to Read Xml File Contents in Jquery and Display in HTML Elements
Change <Select>'s Option and Trigger Events with JavaScript
Performance Differences Between Visibility:Hidden and Display:None