I am looking to create a script in JavaScript that can detect whether a sidebar has the class "active" or not. The sidebar is controlled by Bootstrap's toggle button, which adds the "active" class when clicked.
<button type="button" id="sidebarCollapse" class="btn btn-info" style="font-family:'Poppins'; position:absolute; z-index:9; margin-left:7vh; margin-top:2vh;font-size: 1.5em">
<span class="glyphicon glyphicon-filter"></span> Filter
</button>
Here is the CSS styling:
#sidebar {
background: #202020;
color: #fff;
display:inline-block;
}
#sidebar.active {
margin-left: -250px;
}
And here is the JavaScript code:
//Check if the sidebar has the 'active' class
var sideBar = document.getElementById('sidebar')
console.log(sideBar.className)
if (sideBar.className == ('active')){
console.log('active')
}
else {console.log('not active')}
Just to clarify, the 'active' class is only added to the sidebar when the sidebarCollapse button is clicked and removed when it is clicked again. However, the above code is not functioning properly. It always logs 'not active', even when the sidebar is visibly marked as 'active'. I would like it to dynamically recognize the status of the sidebar (active or not active).
var sideBar = document.getElementById('sidebar');
console.log(sideBar.className)
if (sideBar.classList.contains('active')){
console.log('active')
}
else {console.log('not active')}
Below are images showcasing the HTML with both states of the sidebar (active/not active):