jQuery addClass example
Change class name on click in jQuery
by Pradeep K. Pant
HTML
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Accordion jQuery demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css">
<link rel="stylesheet" type="text/css" href="css/show-hide-accordion.css" />
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
</head>
<body>
<button class="menu_accordion">Top</button>
<div class="menu_panel">
<a href="#" class="menu_panel_button"> <i class="fas fa-user fa-fw" aria-hidden="true"></i>Child1</a>
<a href="#" class="menu_panel_button"> <i class="fas fa-user fa-fw" aria-hidden="true"></i>Child2</a>
<a href="#" class="menu_panel_button"> <i class="fas fa-user fa-fw" aria-hidden="true"></i>Child3</a>
</div>
<script src="js/show-hide-accodion.js"></script>
</body>
</html>
CSS
.menu_accordion {
background-color: #2A3F54;
color: #fff;
cursor: pointer;
padding: 10px 10px 10px 15px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 13px;
transition: 0.4s;
}
.menu_accordion:hover {
background-color: rgb(115,135,156);
color: #fff;
}
.menu_accordion:after {
content: '\002B';
color: #fff;
font-weight: bold;
float: right;
margin-left: 5px;
}
.menu_accordion i,
.menu_panel_button {
margin-right: 5px;
}
.menu_panel {
padding: 0;
background-color: #fff;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
.menu_panel_button {
width: 100%;
color: white;
text-decoration: none;
text-align: left;
font-size: 13px;
transition: 0.4s;
cursor: pointer;
display: inline-block;
padding: 7px 0 7px 30px;
border-left: 5px solid white;
background: rgb(115,135,156);
}
.menu_panel_button:hover {
border-left: 5px solid rgb(115,135,156);
}
JavaScript
var acc = document.getElementsByClassName("menu_accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[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";
}
});
}