In HTML can I disable user interaction with an entire DOM sub-tree via CSS?
Use CSS pointer-events
property on an element to disable user interaction on it and its descendants.
div.disabled { pointer-events: none; }
You could also use the user-select
property to further restrict the user interaction of text selection.
div.disabled { user-select: none; }
Note that the user-select
property may need vendor prefixes.
However, these CSS properties will not disable keyboard interactions which could happen by way of tabbing into the descendants.
As per this reference -- https://html.spec.whatwg.org/multipage/interaction.html#inert-subtrees; there is a proposal of an inert
property but it is not yet implemented by browsers.
So, as of now you will resort to Javascript to disable keyboard interactions. Just wire up the keydown
event with capture
and set the returnValue
to false
. Do not forget to allow Tab key to allow for an escape out, otherwise the focus could get trapped.
var noInteracts = document.getElementsByClassName('disabled');
[].map.call(noInteracts, function(elem) {
elem.addEventListener("keydown", function(e) {
if (e.keyCode != 9) { // allow tab key to escape out
e.returnValue = false;
return false;
}
}, true);
});
You could also hide the highlight-outline on focus of inputs by this CSS:
div.disabled *:focus { outline: 0; }
Below is a demo with all of the above techniques combined.
Demo fiddle: http://jsfiddle.net/abhitalks/hpowhh5c/5/
Snippet:
var noInteracts = document.getElementsByClassName('disabled');
[].map.call(noInteracts, function(elem) {
elem.addEventListener("keydown", function(e) {
if (e.keyCode != 9) {
e.returnValue = false;
return false;
}
}, true);
});
div.disabled {
pointer-events: none;
-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none;
user-select: none;
}
div.disabled *:focus { outline: 0; }
This is normal
User interaction is disbled here
Lorem ipsum