I have a div
with some input fields:
<div class="container">
<input id="input-a" type="text" name="input-a" tabindex="0">
<input id="input-b" type="text" name="input-b" tabindex="0">
</div>
In special cases I have to disable this div by adding the following .disable
class to the div:
.disable {
pointer-events: none;
opacity: .15;
}
This way it is no further possible to select the input fields with the mouse. However, you can still access the fields by tabbing into them via tab
key. I have tried to add tab-index: -1
to the .disable class, but that just gives me an Invalid property name
in the Firefox developer tools (tabindex without hyphen as well).
Is there any way to disable the input fields through CSS comepletely so that no access at all can be guaranteed?
2
Answers
You cannot directly manipulate the tabindex attribute via CSS, as it is an HTML attribute responsible for defining the tab order of elements on a page. To achieve the desired behavior of making input fields inaccessible when applying the .disable class to the container div, JavaScript is necessary. You can dynamically set the tabindex attribute to -1 on the input elements under these conditions.
Here’s an example of how you can do this with JavaScript:
In this example, the
disableInputs()
function applies the.disable
class to the container div, effectively rendering the input elements unselectable through both mouse and keyboard interaction by setting theirtabindex
attributes to -1. Conversely, theenableInputs()
function removes the.disable
class and resets thetabindex
values to 0, restoring the ability to select the inputs.I don’t think it is achievable by only use of CSS. I wasn’t able to find any way of setting up the tab index value with CSS.
Only way I can image if it comes to vanilla JavaScript would be to select the elements and add the
disable
attribute (https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/disabled) to the inputs:Additionally, instead of adding the
disable
class you can use:disable
pseudo class to style the elements as you want them. (https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled)In that case the code would look like this:
Hope that helps.
Note: I changed the container class into id of the container, just to be more specific about what we want to disable. This solution can be also used with the class name – use
<div class="container"></div>
and then instead of#container
selector will be.container
. This can be used for example for grouping of the inputs if you want to apply same logic to different elements.Note 2: I also change the tab indexes from zero to ascending values, so it can be easily observed what is actually happening when you tab through them.