Why Answer Now?
A developer with whom I work intends to use these answers as a reference. I believe a better answer could benefit him and others.
What Does This Answer Provide?
It provides both provide a solution that (a) is semantically accurate, (b) considers accessibility, and (c) uses existing answers; and review the existing answers.
Any Additional Notes?
How should a <div>
behave differently when "disabled"? It is a "generic container"… nothing to disable. I use the behavior of existing answers:
- prevent mouse interaction with child elements
- identify the
<div>
as "disabled" to certain software
Proposed Solution
Note: This solution uses Functional Components syntax.
div.is-disabled
{
pointer-events: none;
opacity: 0.7;
}
/**
* Render a button and an element whose content it "disables"
*
* NOTE: The "disabling" prevents user interaction with its children and to reduce the opacity of the entire element.
*
* @prop {Object} props
* @prop {*} props.children - Any React-parseable children as the content
* @function
*/
function MyComponent({ children }) {
/** Whether content is disabled */
let isDisabled = false;
/**
* When user clicks on element that should trigger "disabling" a div
* @param {UIEvent} event
* @function
*/
const onClick (event) => {
if (!isDisabled) {
isDisabled = true;
}
}
render (
<>
<div
aria-disabled={isDisabled}
className={(isDisabled) ? 'is-disabled' : ''}
>
{children}
</div>
<button onClick={onClick}>
Disable Content
</button>
</>
);
}
Review of Existing Answers
Great. This suggests a meaning for "disable a <div>
", and a solution.
But, the markup concerns me.
- The
<div>
tag does not have a disabled
attribute ^1 ^2.
- Using other elements' standard attribute on an element without such an attribute can confuse new developers.
- Custom attributes (last I checked) require a
data-
prefix.
Answers question accurately—no faults.
But, I think the aria-disabled
attribute only "disables" the div for some user experiences. Visual browser users would not experience this <div>
as being "disabled".
I agree entirely.
But, this solution does not "disable" a div. The original poster may not be asking the question appropriately, and I support you leading him toward a <button>
.