Disable a href Link using CSS

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.

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.

/* * Use your preferred method of targeting a link * * document.getElementById('MyLink'); * document.querySelector('.link-class'); * document.querySelector('[href="https://unfetteredthoughts.net"]'); */ // "Disable" link by removing the href property link.href = ''; // Enable link by setting the href property link.href = 'https://unfetteredthoughts.net';

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.

Читайте также:  Css svg background image sprite

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.

// After using preferred method to target link link.addEventListener('click', function (event) < if (this.parentElement.classList.contains('isDisabled')) < event.preventDefault(); >>);

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.

.isDisabled < cursor: not-allowed; opacity: 0.5; >a[aria-disabled="true"] < color: currentColor; display: inline-block; /* For IE11/ MS Edge bug */ pointer-events: none; text-decoration: none; >

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?

document.body.addEventListener('click', function (event) < // filter out clicks on any other elements if (event.target.nodeName == 'A' && event.target.getAttribute('aria-disabled') == 'true') < event.preventDefault(); >>);

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.

function disableLink(link) < // 1. Add isDisabled class to parent span link.parentElement.classList.add('isDisabled'); // 2. Store href so we can add it later link.setAttribute('data-href', link.href); // 3. Remove href link.href = ''; // 4. Set aria-disabled to 'true' link.setAttribute('aria-disabled', 'true'); >function enableLink(link) < // 1. Remove 'isDisabled' class from parent span link.parentElement.classList.remove('isDisabled'); // 2. Set href link.href = link.getAttribute('data-href'); // 3. Remove 'aria-disabled', better than setting to false link.removeAttribute('aria-disabled'); >

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. Seriously folks, just don’t do it.

Источник

Можно ли скрыть заголовок от ссылки с помощью CSS?

Из-за jQuery Mobile заголовок будет появляться после появления определенных событий (в основном каждый раз, когда элемент привязки перерисовывается). Поэтому я надеюсь скрыть заголовок с помощью CSS. Что-то вроде:

не работает, поскольку он скрывает весь элемент привязки. Я хочу скрыть только заголовок. Возможно ли это? Всплывающее окно не должно отображаться.

@Gatekeeper Это всплывающая подсказка, созданная jQuery Mobile, поэтому я в значительной степени застрял с ней. Я просто хочу это скрыть 🙂

Другая идея (гораздо менее элегантная, чем то, что вы ищете, но выполняет свою работу): вы можете изменить поведение jQuery Mobile. Я бы не стал напрямую менять исходный код (обычно это не очень хорошая практика), но вы могли бы написать расширение, которое подключается и удаляет заголовок после того, как он рендерит элементы.

Вы говорите, что невозможно сделать $(«a»).attr(«title», «»); в твоем случае. Это потому, что у вас есть какие-то ограничения, или потому что вы пытались, и это не сработало? Если это просто не сработало, вам может потребоваться сделать $(‘a’).prop(‘title’, »); так как attr ! = prop в jQuery> = 1.6 ..

@Aaron Аарон Да, это то, что я сделал. Мой плагин создает слайдер, который выполняет шаги в шестнадцатеричном формате. Я зарегистрировал обработчики для «slidestop» и «mouseover», скрывая атрибут title, но при перетаскивании ползунка он все еще показывает.

@Noyo Contraints. Я делал $ («a»). Attr («title», «») во многих событиях, но есть некоторые, в которые я не могу зацепиться. Смотри мой ответ Аарону.

Вы случайно не знаете, как плагин создает эту подсказку? Если это так, вы можете быть нацелены на это и скрыть его вместо a .

@BoltClock jQuery Mobile обновляет его каждый раз в своем методе обновления, поэтому он не является частью плагина.

5 ответов

Использование следующего свойства CSS гарантирует, что текст атрибута title не появляется при наведении:

Имейте в виду, что JS является лучшим решением, так как это свойство CSS гарантирует, что элемент никогда не является объектом каких-либо событий мыши.

Да @Hafenkranich, поэтому в своем ответе я написал: «Имейте в виду, что JS является лучшим решением, поскольку это свойство CSS гарантирует, что элемент никогда не будет целью каких-либо событий мыши».

В соответствии с предложением @boltClock, я скажу, что я не считаю, что здесь подходит CSS-решение, так как браузер решает, что делать с атрибутом title ссылки, или что-то в этом роде. Насколько мне известно, CSS не может решить эту проблему.

Как уже упоминалось, использование jQuery для замены заголовка пустой строкой не будет работать, поскольку в некоторых случаях jQuery mobile переписывает их. Это, однако, будет работать независимо от JQM и не предполагает полного удаления атрибута title, что важно для SEO.

$('a["title"]').on('mouseenter', function(e)< e.preventDefault(); >); 

Я изменил свой исходный код $(‘body’).on(‘mouseenter’) на этот после тестирования. Это подтверждается на работу.

ну, @BoltClock, это потому что это не так. ОП только сказал, что что-то вроде jquery-скрипта, включенного в HE / SHE, не будет работать. Поскольку он использует jquery mobile, я по праву предполагаю, что jquery используется для его проекта и что ответ jquery (который работает) будет честной игрой.

Да, я говорю, что вам нужно упомянуть, что это не (возможно) с CSS, потому что вопрос специально задан, чтобы сделать это с помощью CSS, а не jQuery.

Источник

The href attribute specifies the URL of the page the link goes to and this attribute specifies the location (URL) of the external resource (most often a style sheet file).To disable a href link we need to use various attributes along with it.

Syntax

In HTML we use the following syntax to use href attribute.

In this, we can also use the tag instead of the tag.

Multiple Approaches

We have provided the solution in different approaches.

Let’s see the program along with its output one by one.

Approach-1: By Using pointer-events property

In this method, the href within a class is used to deactivate the link inside the a> tag, and the pointer-events CSS property is used to control whether or not the element on the page must respond when clicked.

A specific visual element’s ability to become the target of pointer events is controlled by the pointer-events CSS property, which specifies whether or not they can.

We have used the colour and text-decoration properties in addition to the pointer-events property.

It should be noted that pointer-events are an experimental use of CSS for non-SVG elements. Due to numerous unresolved concerns, the functionality was originally intended for the CSS 3 UI draught specification but has now been moved to CSS 4.

Syntax

The following is the generic syntax to pointer-events CSS property where in parameter it take property accordingly.

Example

The following program we are using internal CSS, creating class inside the style tag along with the pointer-event property set to none to make the href link disable when used within the tag by adding the same class to it to make the text added in the tag disable in HTML programming language.

     .disable-link Link   

In this method, the href link attribute is used in conjunction with the pre-defined bootstrap properties from class disabled to make the supplied link disabled.

To attempt to deactivate the link functionality of a> and this class while making it visually appear disabled, the.disabled class utilises pointer-events: none.

Example

In this program, we have used the .disabled class which is the inbuilt class of bootstrap with the where we have used the href attribute with link to make the same link diable to any user in the HTML programming language.

Supported Browsers − The browsers supported by pointer-events Property are listed below −

  • Google Chrome 1.0
  • Edge 12.0
  • Internet Explorer 11.0
  • Firefox 1.5
  • Opera 9.0
  • Safari 4.0

In this article, we explored how to disable the href link in HTML using two different approaches.

Источник

Оцените статью