Burger menu icon opens and closes a hidden sidebar, at the same time I want the icon to change to an X when the sidebar is open.
Button
<span style="font-size:16px;cursor:pointer" onclick="toggleNav()"><i onclick="myFunction(this)" class="fas fa-bars"></i> </span>
Menu Scripts
<script>
function toggleNav() {
var sidenav = document.getElementById("mySidenav"),
main = document.getElementById("main");
sidenav.style.width = sidenav.style.width === "250px" ? '0' : '250px';
wrapper.style.marginLeft = wrapper.style.marginLeft === "250px" ? 'auto' : '250px';
}
</script>
<script>
function myFunction(x) {
x.classList.toggle("fas fa-times");
}
</script>
Probably making a glaringly obvious mistake but I've googled as many times as I can and still can't figure it out.
You cannot toggle multiple classes like you did
You have to do two calls
function toggleNav() {
/* var sidenav = document.getElementById("mySidenav"),
main = document.getElementById("main");
sidenav.style.width = sidenav.style.width === "250px" ? '0' : '250px';
wrapper.style.marginLeft = wrapper.style.marginLeft === "250px" ? 'auto' : '250px';*/
}
function myFunction(x) {
x.classList.toggle("fa-bars");
x.classList.toggle("fa-times");
}
i {
height: 20px;
width: 20px;
background-color: red;
display: block;
}
<span style="font-size:16px;cursor:pointer" onclick="toggleNav()"><i onclick="myFunction(this)" class="fas fa-bars"></i> The red square represent your icon</span>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments