Looking to create a toggle effect for a dropdown box that appears and disappears when a button is clicked.
var clickState = false;
$("#show").on("click", function() {
if (!clickState) {
$(".animated").removeClass("off");
refreshElement($(".animated"));
$(".animated").addClass("on");
clickState = true;
} else if (clickState) {
$(".animated").removeClass("on");
refreshElement($(".animated"));
$(".animated").addClass("off");
clickState = false;
}
});
function refreshElement(e) {
var newElement = e.clone(true);
e.remove();
$(".container").append(newElement);
}
.controls {
text-align: center;
}
button {
display: inline-block;
}
.textbox {
width: 280px;
margin: 0 auto;
background: tomato;
padding: 10px;
}
.animated {
max-height: 0;
overflow: hidden;
animation-name: none;
animation-duration: 0.5s;
animation-fill-mode: forwards;
}
.triangle {
content: " ";
width: 0;
height: 0;
border: 10px solid;
border-color: transparent transparent tomato transparent;
position: relative;
left: 50%;
top: -9px;
margin-left: -7px;
}
.on {
animation-name: slideOpen;
animation-direction: normal;
}
.off {
animation-name: slideOpen;
animation-direction: reverse;
}
@keyframes slideOpen {
0% {
max-height: 0px;
padding: 0px;
}
100% {
max-height: 150px;
}
}
<div class="controls">
<button id="show">Show div</button>
</div>
<div class="container">
<div class="animated">
<span class="triangle"></span>
<div class="textbox">text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Utilizing a clickState boolean variable to toggle the visibility of the dropdown box. The entire div is cloned and recreated to refresh the animation properly. The animation is controlled by applying and removing classes using the .addClass() method. While navigating through animation is new to me, I acknowledge the complexity of the code and will continue to refine it.