Javascript Dont Allow Link to Be Clicked Again

The topic of disabling links popped upward at my piece of work the other twenty-four hours. Somehow, a "disabled" anchor style was added to our typography styles final year when I wasn't looking. There is a problem though: there is no existent fashion to disable an <a> link (with a valid href attribute) in HTML. Non to mention, why would you even desire to? Links are the footing of the web.

At a certain point, information technology looked like my co-workers were non going to have this fact, so I started thinking of how this could be achieved. Knowing that it would accept a lot, I wanted to prove that it was non worth the try and code to back up such an anarchistic interaction, simply I feared that by showing information technology could be washed they would ignore all my warnings and just apply my example as proof that information technology was OK. This hasn't quite shaken out for me yet, but I figured we could go through my inquiry.

First, things showtime:

Merely don't exercise it.

A disabled link is not a link, it's but 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 way, but this is misleading. You lot demand to do more than just make a link look disabled if you really desire to disable it.

Surefire way: remove the href

If you accept decided that y'all 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 aspect on a and area elements is not required; when those elements practice not have href attributes they practice not create hyperlinks.

An easier to sympathize definition from MDN:

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

Hither is basic JavaScript code to prepare and remove the href attribute:

          /*   * Apply your preferred method of targeting a link  *  * certificate.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';        

Styling this via CSS is also pretty straightforward:

          a {   /* Disabled link styles */ } a:link, a:visited { /* or a[href] */   /* Enabled link styles */ }        

That's all you lot demand to do!

That'southward not enough, I want something more complex so that I can await smarter!

If you just absolutely have to over-engineer some farthermost solution, here are some things to consider. Hopefully, you will accept listen and recognize that what I am about to show you is non worth the effort.

First, nosotros demand to style our link so that it looks disabled.

          .isDisabled {   color: currentColor;   cursor: not-allowed;   opacity: 0.five;   text-decoration: none; }        
          <a form="isDisabled" href="https://unfetteredthoughts.net">Disabled Link</a>        

Setting color to currentColor should reset the font colour back to your normal, not-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, nosotros take 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 one-half. According to WCAG, disabled elements practice not need to encounter colour contrast guidelines. I call back this is very risky since information technology's basically plain text at this indicate, and dropping the opacity in half would make information technology very hard to read for users with low-vision, another reason I detest this. Lastly, the text decoration underline is removed every bit this is ordinarily the best indicator something is a link. At present this looks like a disabled link!

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

          .isDisabled {   ...   pointer-events: none; }        

Ok, we are done! Disabled link achieved! Except, it'due south only really disabled for mouse users clicking and bear on users tapping. What about browsers that don't back up pointer-events? According to caniuse, this is not supported for Opera Mini and IE<11. IE11 and Edge actually don't support arrow-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 nosotros have to change our markup and CSS…

          .isDisabled {   cursor: not-allowed;   opacity: 0.5; } .isDisabled > a {   color: currentColor;   display: inline-block;  /* For IE11/ MS Edge issues */   pointer-events: none;   text-ornament: none; }        
          <span form="isDisabled"><a href="https://unfetteredthoughts.internet">Disabled Link</a></span>        

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

What near keyboard users? Keyboard users volition use the ENTER key to activate links. arrow-events are only for pointers, there is no keyboard-events. We likewise need to foreclose activation for older browsers that don't support pointer-events. Now we accept to introduce some JavaScript.

Bring in the JavaScript

          // After using preferred method to target link link.addEventListener('click', function (effect) {   if (this.parentElement.classList.contains('isDisabled')) {     consequence.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 existence disabled. The disabled attribute is non valid on links, simply nosotros can use aria-disabled="true".

          <span class="isDisabled"><a href="https://unfetteredthoughts.cyberspace" aria-disabled="true">Disabled Link</a></bridge>        

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

          .isDisabled {   cursor: not-allowed;   opacity: 0.five; } a[aria-disabled="truthful"] {   colour: currentColor;   display: inline-cake;  /* For IE11/ MS Border issues */   pointer-events: none;   text-ornamentation: none; }        

Now our links wait 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 chemical element that has a click listener. This is because of developer trend to make not-interactive elements similar div and span as pseudo-interactive elements with a unproblematic listener. Null we tin can do about that here. Everything we have done to remove any indication that this is a link is foiled past 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.torso.addEventListener('click', part (event) {   // filter out clicks on whatsoever other elements   if (consequence.target.nodeName == 'A' && consequence.target.getAttribute('aria-disabled') == 'truthful') {     effect.preventDefault();   } });        

Are we done? Well, not really. At some point we will need to enable these links so nosotros demand to add together boosted code that will toggle this land/behavior.

          function disableLink(link) { // 1. Add together isDisabled class to parent span   link.parentElement.classList.add('isDisabled'); // ii. Store href so nosotros 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('information-href'); // three. Remove 'aria-disabled', better than setting to fake   link.removeAttribute('aria-disabled'); }        

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

Seriously folks, but don't do it.

montieltherelies.blogspot.com

Source: https://css-tricks.com/how-to-disable-links/

0 Response to "Javascript Dont Allow Link to Be Clicked Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel