inert Global Attribute and its Usecases
As a web developer, you may encounter situations where you need to disable user interaction with certain elements on a webpage. One relatively recent way to achieve this is by using the
inert HTML global attribute. This attribute makes an element and all of its descendants non-interactive and un-focusable, effectively disabling user input events such as clicks, touches, and keyboard events.
To use the inert attribute, simply add it to the HTML element you want to make inert:
<button inert>Not working!</button>
If we add some click handlers to those buttons you can see how the first button is non-interactive while the second one works as expected.
inert property will also apply to all descendents so you can disable entire sections of your page.
<button>Also not working!</button>
Probably the most common usecase for the
inert property would be for creating a modal. When a modal is opened you do not want the user to be able to interact with the content beneath it so you can set that as
inert while keeping the modal
div and the overlay
div interactable so that it can be closed when needed.
inert property can be used when creating complex navigation especially with dropdowns. For example When a nested menu is opened you could make the rest of the menu
inert so that users don't accidentally click outside of the section they have currently selected.
Complex forms can also benefit from the
inert property as you are able to fully guide the user through filling out the information without providing too many options at once and confusing them.
More advanced experiences such as games or multimedia can be enhanced by using the
inert property to disable elements that shouldn't be interacted with at a given time. For example if you have a game that involves dragging and dropping objects within the page then you could disable some of the other buttons during this actions so they are not accidentally clicked.
While relatively new, the
inert property is supported by all major browsers with the exception of Firefox.
Disabling elements should be done only when you have a good reason, as this can cause several accessibility issues. First there is no visual indication that an element is disabled so it is up to the engineers to provide some sort of cue. Second, the elements with
inert set to
true may be removed from the accessibility tree for assistive technologies.
inert HTML global attribute is a powerful tool that can be used to disable user interaction with elements on a webpage. By using the inert attribute strategically, you can create more intuitive and user-friendly experiences for your website's visitors. However it is important to use it sparingly and in addition to other approaches as it can have negative impacts on accessibility.