Disable a HTML <a> link/anchor tag · Code with Hugo (2024)

/ #html#javascript

Here are 2 ways to disable a HTML <a> link/anchor element using CSS or by using inline JavaScript.

Table of Contents

Disable HTML anchor with CSS pointer-events: none

To disable a HTML anchor element with CSS, we can apply the pointer-events: none style.

pointer-events: none will disable all click events on the anchor element.

For example:

<a href="https://google.com" style="pointer-events: none">Google.com</a>

The pointer-events can be set using CSS properties and selectors:

<style>.disabled-link { pointer-events: none;}</style><a href="https://google.com" class="disabled-link">Google.com</a>

This is a great option when you only have access to class or style attributes. It can even be used to disable all the HTML links on a page.

<style>/* not recommended */a { pointer-events: none;}</style><a href="https://google.com">Google.com</a>

We’ve now seen how to disable an HTML anchor/link element (a tag) using pointer-events: none, which can be done without touch the existing href attribute using styles.

Next we’ll see how to disable an HTML anchor/link element using inline JavaScript inside of the href attribute.

Disable HTML anchor with inline JavaScript href="javascript:void(0)"

The following link is disabled using inline JavaScript in the href attribute.

<a href="javascript:void(0)">Google.com</a>

This can be useful when combined with a JavaScript library like Alpine.js:

<div x-data="{ disabled: false }"> <a :href="disabled ? 'javascript:void(0)': 'https://google.com'">Google.com</a> <button @click="disabled = !disabled">toggle disabled</button></div>

The examples in this post can be found on CodePen.

Photo by Jonathon Young on Unsplash

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.

Find out more

or

Join 1000s of developers learning about Enterprise-grade Node.js & JavaScript

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.

Disable a HTML <a> link/anchor tag

Disable a HTML <a> link/anchor tag · Code with Hugo (2024)
Top Articles
Latest Posts
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 6173

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.