6.1 <details> Tag
HTML5 brought in the <details>
and <summary>
elements, which are used to create interactive collapsible content blocks.
These elements let users expand and collapse content, enhancing user interaction and saving space on a webpage.
The <details>
element is used to create a block that can be collapsed or expanded. You can put any HTML content inside it.
Upon expansion, <details>
shows the nested content, while collapsing it hides the content.
Syntax:
<details>
<summary>Title</summary>
<!-- Hidden content -->
</details>
Open Attribute:
If the attribute is present, the <details>
block will be expanded by default.
Example of using <details>
<details open>
<summary>Main Information</summary>
<p>This info is visible by default because the open attribute is set.</p>
</details>
Explanation
<details>
: creates a container for hidden content.<summary>
: defines a title that is always visible and clickable to toggle the content display.
6.2 <summary> Tag
The <summary>
element is used inside <details>
to create a title. This title is always visible and acts as a control
to expand or collapse the <details>
block's content.
Syntax:
<details>
<summary>Title</summary>
<!-- Hidden content -->
</details>
Usage Example:
<details>
<summary>More Details</summary>
<p>This is hidden content that becomes visible when the block is expanded.</p>
</details>
Advantages of using <details> and <summary>
- Improved User Experience: users can control what content they want to see.
- Space Saving: hides large amounts of information behind interactive titles.
- Semantic Markup: enhances the HTML document's structure and its accessibility for users and search engines.
6.3 Interaction with JavaScript
The <details>
and <summary>
elements can be easily controlled using JavaScript for creating more interactive web pages.
JavaScript Usage Example:
<details>
<summary>More Details</summary>
<p>This is hidden content that becomes visible when the block is expanded.</p>
</details>
<details open>
<summary>Main Information</summary>
<p>This info is visible by default because the open attribute is set.</p>
</details>
<button id="toggleDetails">Collapse/Expand</button>
// Find the button with id 'toggleDetails' and add a 'click' event listener
document.getElementById('toggleDetails').addEventListener('click', () => {
// Find all 'details' elements on the page
document.querySelectorAll('details').forEach(detail => {
// Toggle the 'open' attribute of each 'details' element
detail.open = !detail.open;
});
});
Explanation:
- Collapse/Expand Button: controls the state of all
<details>
elements on the page - Click Event: toggles the open attribute for all
<details>
elements
GO TO FULL VERSION