When I use the new details
tag in combination with a summary
I would then like to disable the generated input. I thought that
JavaScript
x
2
1
<details open disabled>
2
could do the trick, but sadly it doesn’t work.
How can one disable the details element?
Advertisement
Answer
Instead of using the non-existent disabled
attribute, you can set a click handler on the <details>
element, and prevent the default event behavior from there. Quick and dirty way is:
JavaScript
1
5
1
<details open onclick="return false">
2
<summary>Click here</summary>
3
<p>content</p>
4
</details>
5
The proper way to do it would be using addEventListener
:
JavaScript
1
11
11
1
<details id="mydetails" open>
2
<summary>Click here</summary>
3
<p>content</p>
4
</details>
5
6
<script>
7
document.getElementById('mydetails').addEventListener('click', function(e) {
8
e.preventDefault();
9
});
10
</script>
11
To solve the focus problem you mentioned in the comments, add tabindex="-1"
as an attribute of <summary>
to prevent it from getting keyboard focus. Please note that I’m not sure if that will work on every browser, and that a focus
event will still be triggered on click even with the attribute.