Перейти к содержимому

Как сделать ссылку неактивной в html

  • автор:

Disable a HTML <a> link/anchor tag

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

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.

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

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.

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.

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

The examples in this post can be found on CodePen.

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.

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

Hugo Di Francesco

Co-author of «Professional JavaScript», «Front-End Development Projects with Vue.js» with Packt, «The Jest Handbook» (self-published). Hugo runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon, Elsevier and (currently) Eurostar.

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.

Tips For Students Choosing Their First Programming Language

More and more colleges offer their students the opportunity to try their hand in coding. With technologies continuing making massive inroads people’s our everyday lives, such professions as a computer programmer, web developer, software engineer, mobile app developer, and others ranks among the best paying and on-demand. No wonder, so many students, even those who initially chose completely different majors, strive to become conversant with popular programming languages. Being able to write code and program is not only promising, it’s prestigious. But slews of your learners find themselves plagued by some concerns and doubts we’ll try to dispel in today’s article. What’s more, we’ll help you answer the hardest questions most beginners ask themselves when tackling programming and choose the programming language you’ll be most comfortable with. .

Hugo Di Francesco

An accessible Alpine.js menu toggle

The “Hello World” of JavaScript frameworks and libraries seems to have become the todo app. In the case of Alpine.js a todo app is almost too large to showcase Alpine’s core benefits and use case. Another issue with a lot of JavaScript examples is that they forego accessibility. Therefore we won’t be building a todo app but an accessible navigation menu. Our menu is as follows (read on for a breakdown of how it’s built). .

Hugo Di Francesco

Как сделать ссылку некликабельной с помощью CSS

Когда вы создаете веб-страницу, иногда может возникнуть необходимость отключить ссылку на определенном элементе. В этой статье мы расскажем, как сделать ссылку некликабельной с помощью CSS.

Использование CSS свойства pointer-events

Самый простой способ сделать ссылку некликабельной — это использование CSS свойства pointer-events. Данный способ позволяет отключить кликабельность элемента, но не удаляет ссылку. Вот пример кода:

Здесь мы создаем класс «disabled» для ссылки, которую хотим сделать некликабельной, и задаем ему свойство pointer-events со значением «none».

Использование CSS свойства text-decoration

Еще один способ сделать ссылку некликабельной — это убрать ее стандартное оформление. Для этого мы можем использовать CSS свойство text-decoration. Вот пример кода:

Здесь мы задаем класс «disabled» для ссылки и устанавливаем ему значение text-decoration: none, которое убирает подчеркивание ссылки. Мы также устанавливаем свойство cursor: default, чтобы курсор не менял свой вид при наведении на некликабельную ссылку.

Использование атрибута href

Еще один способ сделать ссылку некликабельной — это удалить ее атрибут href. Это приведет к тому, что при нажатии на ссылку ничего не произойдет. Вот пример кода:

Здесь мы добавляем класс «disabled» для ссылки и удаляем атрибут href, задав его значение «#». Это сделает ссылку некликабельной.

В заключение, существует несколько способов сделать ссылку некликабельной с помощью CSS. Выбор зависит от того, что вы хотите добиться и как вы хотите, чтобы ваша страница выглядела.

Как сделать HTML ссылку некликабельной (неактивной)?

Пример CSS кода для создания некликабельной (неактивной) HTML ссылки. Добавляем в CSS код такую запись с классом:

В HTML коде устанавливаем для нективных ссылок класс disabled

Комментировать

СПАСИБО)) простой вариант решения)))

И зачем такие заморочки, если можно просто прописать ссылку, не добавляя <a href. ?

Есть 2 важных преимущества:

  1. Стилизация неактивной ссылки. Вам всё равно придется использовать CSS стили для того, чтобы скрыть подсветку ссылки при наведении курсора.
  2. Удобство для разработчика. Данный вариант удобен (необходим) при разработке веб-приложения, так так дает возможность задать стилизацию и быстро найти неактивные ссылки в коде.

Очень быстро нашел нужную информацию, большое спасибо.

Небольшая поправочка, команда pointer-events: none ; подойдёт на блокировки клика по JavaScript’ам с некоторых сайтов, при клике на скрипт идёт пересылка на сайт.

Это решение не будет работать в IE.

Для IE есть следующий метод, он немного хардкодный но работает) Ссылку можно обернуть в span и перекрыть кликабельность ссылки псевдоэлементом на span.

Спасибо! Интересный вариант решения проблемы для IE.

При работе на теме лаерс вордпресс есть возможность управлять CSS но нет возможности править HTML. Есть способ для ИЕ с помощью только CSS?

Спасибо! Лаконично и эффективно.

Подскажите, если в документе 3 ссылки. И надо, чтобы при нажатии на одну из них, остальные исчезали (именно ссылки исчезали, а не содержимое, которое внутри ссылок).

Т.е., есть раскрывающийся доп.текст при нажатии на фразы «да», «нет», «не знаю». Надо чтобы при нажатии допустим на «да», фразы «нет» и «не знаю» пропадали.

Программирую на уровне копипастера) вбил запрос в поисковик, нашел это решение и стал счастливее) Спасибо!

How to Disable Links

The topic of disabling links popped up at my work the other day. Somehow, a “disabled” anchor style was added to our typography styles last year when I wasn’t looking. There is a problem though: there is no real way to disable an <a> link (with a valid href attribute) in HTML. Not to mention, why would you even want to? Links are the basis of the web.

At a certain point, it looked like my co-workers were not going to accept this fact, so I started thinking of how this could be accomplished. Knowing that it would take a lot, I wanted to prove that it was not worth the effort and code to support such an unconventional interaction, but I feared that by showing it could be done they would ignore all my warnings and just use my example as proof that it was OK. This hasn’t quite shaken out for me yet, but I figured we could go through my research.

First, things first:

A disabled link is not a link, it’s just text. You need to rethink your design if it calls for disabling a link.

Bootstrap has examples of applying the .disabled class to anchor tags, and I hate them for it. At least they mention that the class only provides a disabled style, but this is misleading. You need to do more than just make a link look disabled if you really want to disable it.

Surefire way: remove the href

If you have decided that you are going to ignore my warning and proceed with disabling a link, then removing the href attribute is the best way I know how.

Straight from the official Hyperlink spec:

The href attribute on a and area elements is not required; when those elements do not have href attributes they do not create hyperlinks.

An easier to understand definition from MDN:

This attribute may be omitted (as of HTML5) to create a placeholder link. A placeholder link resembles a traditional hyperlink, but does not lead anywhere.

Here is basic JavaScript code to set and remove the href attribute:

Styling this via CSS is also pretty straightforward:

That’s all you need to do!

That’s not enough, I want something more complex so that I can look smarter!

If you just absolutely have to over-engineer some extreme solution, here are some things to consider. Hopefully, you will take heed and recognize that what I am about to show you is not worth the effort.

First, we need to style our link so that it looks disabled.

Setting color to currentColor should reset the font color back to your normal, non-link text color. I am also setting the mouse cursor to not-allowed to display a nice indicator on hover that the normal action is not allowed. Already, we have left out non-mouse users that can’t hover, mainly touch and keyboard, so they won’t get this indication. Next the opacity is cut to half. According to WCAG, disabled elements do not need to meet color contrast guidelines. I think this is very risky since it’s basically plain text at this point, and dropping the opacity in half would make it very hard to read for users with low-vision, another reason I hate this. Lastly, the text decoration underline is removed as this is usually the best indicator something is a link. Now this looks like a disabled link!

But it’s not really disabled! A user can still click/tap on this link. I hear you screaming about pointer-events .

Ok, we are done! Disabled link accomplished! Except, it’s only really disabled for mouse users clicking and touch users tapping. What about browsers that don’t support pointer-events ? According to caniuse, this is not supported for Opera Mini and IE pointer-events unless display is set to block or inline-block . Also, setting pointer-events to none overwrites our nice not-allowed cursor, so now mouse users will not get that additional visual indication that the link is disabled. This is already starting to fall apart. Now we have to change our markup and CSS…

Wrapping the link in a < span > and adding the isDisabled class gives us half of our disabled visual style. A nice side-affect here is that the disabled class is now generic and can be used on other elements, like buttons and form elements. The actual anchor tag now has the pointer-events and text-decoration set to none .

What about keyboard users? Keyboard users will use the ENTER key to activate links. pointer-events are only for pointers, there is no keyboard-events. We also need to prevent activation for older browsers that don’t support pointer-events . Now we have to introduce some JavaScript.

Bring in the JavaScript

Now our link looks disabled and does not respond to activation via clicks, taps, and the ENTER key. But we are still not done! Screen reader users have no way of knowing that this link is disabled. We need to describe this link as being disabled. The disabled attribute is not valid on links, but we can use aria-disabled=»true» .

Now I am going to take this opportunity to style the link based on the aria-disabled attribute. I like using ARIA attributes as hooks for CSS because having improperly styled elements is an indicator that important accessibility is missing.

Now our links look disabled, act disabled, and are described as disabled.

Unfortunately, even though the link is described as disabled, some screen readers (JAWS) will still announce this as clickable. It does that for any element that has a click listener. This is because of developer tendency to make non-interactive elements like div and span as pseudo-interactive elements with a simple listener. Nothing we can do about that here. Everything we have done to remove any indication that this is a link is foiled by the assistive technology we were trying to fool, ironically because we have tried to fool it before.

But what if we moved the listener to the body?

Are we done? Well, not really. At some point we will need to enable these links so we need to add additional code that will toggle this state/behavior.

That’s it. We now have a disabled link that is visually, functionally, and semantically disabled for all users. It only took 10 lines of CSS, 15 lines of JavaScript (including 1 listener on the body), and 2 HTML elements.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *