Identifying the state of the sidebar is key

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):

https://i.sstatic.net/VjXxr.png

https://i.sstatic.net/Gccfm.png

Answer №1

Your code should be functioning correctly. There are two key reasons why it may always display 'not active'.

  1. The code is being executed on page load
  2. You are fetching the sidebar div before it has been opened, therefore the DOM object is not updated afterwards.

To solve this issue, move your code into a function and call that function whenever you need to check the status of the sidebar.

See the sample code below for reference.

function isSidebarOpen() {

  var sideBar = document.getElementById('sidebar');

  if (sideBar.classList.contains('active')) {
    console.log('active')
  } else(console.log('not active'))

}
<div id="sidebar" class="active">
  test
  <button onclick='isSidebarOpen()'>
Check</button>

</div>

Answer №2

To monitor changes in the DOM, use the MutationObserver interface.

Copy and paste the code snippet below to set up the observation:

const targetNode = document.getElementById('sidebarCollapse'); // Select the element to observe

const config = { attributes: true }; // Specify what type of changes to listen for

const callback = function(mutationsList, observer) {
    for(let mutation of mutationsList) {
        if (mutation.type === 'attributes') {
          if (targetNode.classList.contains('active')){
            console.log('active');
            }
        }
    }
};

const observer = new MutationObserver(callback); // Create a new observer instance

observer.observe(targetNode, config); // Begin observing the specified element

View the live demonstration on CodePen.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building numerous pagination features in a single page using Codeigniter

I'm just starting out with codeigniter and I need help creating multiple paginations on one page. I've tried it, but only one pagination is working while the others are giving me errors. Can someone please assist me? I read some suggestions that ...

Using jQuery to manipulate XML: Altering XML content using its ID with jQuery

Trying to modify content within an XML using jQuery has been a bit tricky for me. Based on the examples I've found, I believe the code should look something like this: Javascript: get_verrichtingen: function(){ var self = this; var option = ...

What could be causing this code to keep looping?

This is my submission for a class project. The task given was: "Create a function that will kickstart the program and name it main(). From the main() function, invoke a function named getValue(). The getValue() function will prompt the user to input a num ...

creating a personalized CSS style rule

Can a custom rule be created in CSS using @media for a parent class to make changes based on the class? <div class="parentGreen"> <ul class="ul1"> <li>1</li> <li>2</li> &l ...

What is the best approach to dynamically load html table cell data into a table with changing headers in a React application?

Currently, I am in the process of developing a <table> using React version 0.14.6. This table consists of column headers that are dynamically added to the <thead> section of the table: CourseTable.js: import CourseList from './CourseList ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

The functionality to show the login status is currently malfunctioning

I have a login status indicator section on my homepage which is connected to an ajax-php database. The login button performs two actions when clicked. <input value="Login" type="button" onclick='logInUser(/*function to handle login request*/);upda ...

Dynamic Pagination with MUI Counting

I'm currently utilizing mui react for my current project. Within the Pagination component, I am required to input the count in order to display the total number of pages. For example, with a total of 27 products, and each page displaying 20 products ...

Is it acceptable to employ numerous classes simultaneously?

Instead of applying individual styling attributes like background-color and border to each element, I chose to create a set of classes such as red-background, blue-text, and border-1px... Do you think this approach is acceptable or should I try something d ...

XSLT transformation eliminates HTML elements from mixed content

Can XSLT maintain anchors and other embedded HTML tags within XML? Situation: I'm currently attempting to transform an HTML document into XML using an XSL stylesheet with XSLT. The original HTML content contained anchor tags scattered throughout (e.g ...

css clip-path hover effect restricted to specific shape

In the codepen I created, there are two greyscaled shapes. Currently, it's only possible to hover over one of them, as the original size is a box that overlaps both images. Is there a way to detect the shape being hovered over? Z-index hasn't pro ...

Tips for overriding bootstrap.css file in mvc asp.net using Visual Studio

I am currently working on creating a website using Mvc asp.net in Visual Studio 2013. I have integrated my css file, 'style.css', into the project, but I am encountering unwanted white spaces and margins around headers and other key elements, eve ...

Tips on swapping out a part in ExtJS

Currently, my ExtJS window features a toolbar at the top and loads with a plain Panel at the bottom containing plain HTML. Everything is working smoothly in this setup. However, I now wish to replace this bottom panel (referred to as 'content') w ...

In Firefox, right floated elements vanish when utilizing columns

Utilizing the ol element with column-count and column-gap properties to organize the list into 2 columns, each list item contains a span element floated right. However, I am encountering an issue where the span element is not displayed for certain items li ...

Is the Owl carousel Auto Play feature malfunctioning when hovered over?

I seem to be encountering an issue with the auto play functionality of the owl carousel. I have uploaded and included all the necessary files, and it is functioning properly when initially loaded. The auto play feature works perfectly, but when I hover ove ...

The <main> element is not inheriting the height of its parent

https://i.sstatic.net/PchVf.png Using Chrome DevTools, I removed unnecessary elements from the DOM. The body is set to relative and takes up all available space in the document, which is exactly what I want. https://i.sstatic.net/AzELV.png My toolbar i ...

Navigating through a JSON array of objects within an array of objects in a React Fetch request: How can I effectively utilize mapping?

I successfully retrieved data from the API and was able to display it in the browser. However, I encountered difficulty handling an array of objects in JSON format. The API I used is for countries, some of which have multiple languages. My goal is to dis ...

Understanding the Access-Control-Allow-Headers in preflight response for Wordpress and VueJS

Attempting to retrieve a route from candriam-app.nanosite.tech to candriam.nanosite.tech has proven challenging. Despite various attempts to allow headers, I continue to encounter this CORS error: Access to fetch at 'https://xxxA/wp-json/nf-submission ...

Expanding the width of three floating divs in the center to match the width of the parent container div

In my design, I have a parent container with three inner divs that are floated. The left and right divs have fixed sizes, however, I need the center div to expand and fill the space available within the parent container. <div class="parent-container"&g ...

Use body height set to 100% to measure the scrollTop distance

I am faced with a challenge on my webpage where I need to adjust the height due to scrolling elements, while also detecting the scrollTop() distance to apply some CSS to the navigation bar. Despite setting the body's height to 100%, it appears that I ...