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%;
}
It looks like your element is not getting binded to the click function. You need to use document.ready to check the readiness and bind event.
Below is the working code snippet:
$(document).ready(function(){
$("#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");
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.