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