abergmeier
abergmeier

Reputation: 14052

Disable details/summary

When I use the new details tag in combination with a summary I would then like to disable the generated input. I thought that

<details open disabled>

could do the trick, but sadly it doesn't work.

How can one disable the details element?

Upvotes: 14

Views: 12419

Answers (5)

Ken
Ken

Reputation: 455

I had the same problem but needed an angular 7 solution. So in my template I set the details tag as follows:

<details open (click)="preventAction()">
....
</details>

Then wrote the method in my component like so

  preventAction(): boolean {
    return false;
  }

Upvotes: 0

Joel Nagy
Joel Nagy

Reputation: 321

A very simple way would be to use only CSS. You can still use the disabled attribute or make it a class instead if you would prefer. The pointer-events declaration when set to none makes the summary tag invisible to mouse (elements below the tag would thus be clickable.) Added tabindex="-1" to the summary tags for the disabled ones to eliminate keyboard focus.

<details open disabled>
  <summary tabindex="-1">click here: [disabled]</summary>
  <p>content</p>
</details>

<details open class="disabled">
  <summary tabindex="-1">click here: .disabled</summary>
  <p>content</p>
</details>

<details open>
  <summary>click here: NOT disabled</summary>
  <p>content</p>
</details>

<style>
  details[disabled] summary,
  details.disabled summary {
    pointer-events: none; /* prevents click events */
    user-select: none; /* prevents text selection */
  }
</style>

https://codepen.io/joelnagy/pen/MWKNGGp

Upvotes: 22

Jes&#250;s Loreto
Jes&#250;s Loreto

Reputation: 1

<details class="mydetails" open>
<summary>Click here</summary>
<p>content</p></details>

$(".mydetails").click(function(event) {event.preventDefault();});

Upvotes: -2

bfavaretto
bfavaretto

Reputation: 71918

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:

<details open onclick="return false">
    <summary>Click here</summary>
    <p>content</p>
</details>

The proper way to do it would be using addEventListener:

<details id="mydetails" open>
    <summary>Click here</summary>
    <p>content</p>
</details>

<script>
document.getElementById('mydetails').addEventListener('click', function(e) {
    e.preventDefault();
});
</script>

http://jsfiddle.net/L8HUZ/1/

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.

Upvotes: 11

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

I guess you can return false to prevent the default behaviour:

<details open="" onclick="return false;">
<p>Hello</p></details>

Upvotes: 4

Related Questions