What is An Accordion In HTML ?
In HTML and web development, an "accordion" refers to a user interface component that allows content to be expanded or collapsed. It's typically used to display sections of information that the user can reveal or hide by clicking on headers. This makes it a useful tool for organizing large amounts of content in a limited space, improving the user experience by allowing users to focus on the specific information they are interested in.
Here is a basic example of an accordion using HTML, CSS, and JavaScript:
HTML
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Accordion Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>Accordion Example</h2>
<button class="accordion">Section 1</button>
<div class="panel">
<p>This is the content of section 1.</p>
</div>
<button class="accordion">Section 2</button>
<div class="panel">
<p>This is the content of section 2.</p>
</div>
<button class="accordion">Section 3</button>
<div class="panel">
<p>This is the content of section 3.</p>
</div>
<script src="scripts.js"></script>
</body>
</html>
```
CSS (styles.css)
```css
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}
.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
```
JavaScript (scripts.js)
```javascript
document.addEventListener("DOMContentLoaded", function() {
var accordions = document.getElementsByClassName("accordion");
for (var i = 0; i < accordions.length; i++) {
accordions[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
});
```
Explanation:
1. HTML : The basic structure includes buttons for each section header and a corresponding div for the content.
2. CSS : Styles the buttons and panels, ensuring the panels are hidden by default and expand when active.
3. JavaScript : Adds event listeners to the accordion buttons to toggle the display of the content panels.
This example demonstrates a simple accordion. In real-world applications, you might use libraries or frameworks like Bootstrap, which provide built-in accordion components with more advanced features and better cross-browser compatibility.
Post a Comment