-
Notifications
You must be signed in to change notification settings - Fork 0
/
accordion.html
60 lines (51 loc) · 1.82 KB
/
accordion.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html>
<html>
<head>
<title>Simple Accordion</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="accordion">
<div class="accordion-item">
<button class="accordion-button">Section 1</button>
<div class="panel">
<p>Content for Section 1...</p>
</div>
</div>
<div class="accordion-item">
<button class="accordion-button">Section 2</button>
<div class="panel">
<p>Content for Section 2...</p>
</div>
</div>
<div class="accordion-item">
<button class="accordion-button">Section 3</button>
<div class="panel">
<p>Content for Section 3...</p>
</div>
</div>
</div>
<script>
document.querySelectorAll('.accordion-button').forEach(button => {
button.addEventListener('click', () => {
const panel = button.nextElementSibling;
// Check if the clicked button is currently active
const isButtonActive = button.classList.contains('active');
// Close all panels
document.querySelectorAll('.accordion-item .panel').forEach(p => {
p.style.maxHeight = null;
});
// Deactivate all buttons
document.querySelectorAll('.accordion-button').forEach(b => {
b.classList.remove('active');
});
// If the clicked button was not already active, open its panel
if (!isButtonActive) {
button.classList.add('active');
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
});
</script>
</body>
</html>