Enable or disable an anchor tag with JavaScript/jQuery
This post will discuss how to enable or disable an anchor tag in JavaScript and jQuery.
1. Using JavaScript – preventDefault() function
In pure JavaScript, this is very simple. To prevent an anchor from visiting the specified href, you can call the Event interface’s preventDefault() method on the anchor’s click handle. The code would look like this:
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('a').on("click", function(e) { e.preventDefault(); }); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html> <body> <a href="https://www.bing.com/">Click Me</a> </body> </html> |
You can also add some CSS to make the link appear disabled to the end-user.
JS
|
1 2 3 4 5 6 7 8 9 |
$(document).ready(function() { $('a') .css('cursor', 'default') .css('text-decoration', 'none'); $('a').on("click", function(e) { e.preventDefault(); }); }); |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html> <body> <a href="https://www.bing.com/">Click Me</a> </body> </html> |
2. Using jQuery – Toggle anchor tag
To implement a toggle-like functionality with a click of a button, you can do like following. Note, this uses jQuery.
JS
|
1 2 3 4 5 6 7 8 9 10 11 12 |
$(document).ready(function() { var enabled = true; $('#toggle').click(function() { if (enabled) { $("a").fadeTo("fast", 0.5).removeAttr("href"); } else { $("a").fadeIn("fast").prop("href", "https://www.bing.com/"); } enabled = !enabled; }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<!doctype html> <html lang="en"> <body> <a href="https://www.bing.com/">Click Me</a> <div> <button id="toggle">Toggle Hyperlink</button> </div> </body> </html> |
3. Using jQuery + CSS
With CSS, you can have a .disabled class that blurs the anchor tag. Then you can implement the toggle-like feature with jQuery by applying or removing this class on the anchor tag. On the anchor’s click handle, simply return false if that class is applied to the anchor. The idea is demonstrated below:
JS
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$(document).ready(function() { $('#toggle').click(function() { if ($('a').hasClass('disabled')) { $('a').removeClass('disabled'); } else { $('a').addClass('disabled'); } }); $('a').click(function() { if ($(this).hasClass('disabled')) { return false; } }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<!doctype html> <html lang="en"> <body> <a href="https://www.bing.com/">Click Me</a> <div> <button id="toggle">Toggle Hyperlink</button> </div> </body> </html> |
That’s all about enabling or disabling an anchor tag in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)