I can't toggle a div's class on clicking it in jquery
Expected Behavior : I want to add the close class to the hamburger menu so that it becomes a cross on clicking and want to display an overlay for mobile screens, but currently I just want to figure out how to trigger this onclick event.
Here's the code I am using to do so:
$("#mobile-menu").click(function() {
$(".icon").toggleClass("close");
var x = document.getElementsByClassName("overlay")[0];
if ($(".icon").hasClass("close")) {
x.style.display = "block";
$("body").addClass("modal-open");
} else {
x.style.display = "none";
$("body").removeClass("modal-open");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mobile-menu">
<div class="icon">
<span class="line top"></span>
<span class="line middle"></span>
<span class="line bottom"></span>
</div>
</div>
.line {
position: absolute;
height: 4px;
width: 100%;
background-color: black;
border-radius: 30%;
transition: cubic-bezier(0.26, 0.1, 0.27, 1.55) 0.35s;
}
.icon.close .top {
transform: rotate(45deg);
top: 48%;
}
.icon.close .middle,
.icon.close .bottom {
transform: rotate(-45deg);
top: 48%;
}
overlayclass and its relateddivdoes not exist in your provided example.$("#mobile-menu").cick();or the longer$("#mobile-menu").trigger("click");. If this is not the case (and it probably isn't) please clarify your question and title so it's clear what you are asking.