I want to make toggle nav but unfortunately not working
function navtoggle(){
document.getElementsByClassName('sidebar').classList.toggle('active');
}
</script>
.sidebar.active {
width:0px;
}
I want to make toggle nav but unfortunately not working
function navtoggle(){
document.getElementsByClassName('sidebar').classList.toggle('active');
}
</script>
.sidebar.active {
width:0px;
}
document.getElementsByClassName('sidebar').classList is a HTMLCollection, you must loop through it or pick a specific index
function navtoggle(){
document.getElementsByClassName('sidebar')[0].classList.toggle('active');
}
.active {
color: red;
}
<div class="sidebar">Hello</div>
<button onClick="navtoggle();">Click Me</button>
document.getElementsByClassName() will return a HTMLCollection instead of the single sidebar element you're trying to target. Because classList isn't a property of HTMLCollection, you'll simply get a TypeError when trying to toggle a class on this collection.
If you are sure there is only one element with .sidebar on the page, or that the sidebar you're trying to target is the first in the DOM, you could use document.getElementsByClassName('sidebar')[0]. An alternative approach would be to use document.querySelector('.sidebar'), where you can also pass a more specific selector, such as document.querySelector('aside.sidebar'), to ensure you've selected the right element. For example:
function navtoggle() {
document.querySelector('aside.sidebar').classList.toggle('active');
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
}
body {
width: 100vw;
height: 100vh;
}
.sidebar {
background: #CCC;
width: 15%;
height: 100%;
padding: 1rem;
overflow: hidden;
}
.sidebar.active {
width: 0;
padding: 0;
}
main {
position: absolute;
right: 0;
top: 0;
width: 85%;
height: 100%;
padding: 1rem;
}
button {
padding: .5rem;
margin-top: .5rem;
}
<aside class="sidebar">
This is the sidebar
</aside>
<main>
This is not the sidebar <br>
<button onclick="navtoggle()">Toggle the sidebar</button>
</main>