Ways to determine if the navigation bar is in a collapsed state or not

I am working with a navbar:

<nav id="navbar" class="navbar fixed-top navbar-expand-md navbar-light bg-light">
  <a class="navbar-brand" href="#"></a>
  <button id="toggle" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
    <span class="navbar-toggler-icon"></span>
</button>
  <div class="collapse navbar-collapse text-right" id="navbarNav">
      <ul class="navbar-nav ml-auto">
          <li class="nav-item">
              <a class="nav-link" id="about" href="Gibbs.html"><span><strong>ABOUT</strong></span></a>
          </li>
          <li class="nav-item">
              <a class="nav-link" href="#"><span>NEWS</span></a>
          </li>
          <li class="nav-item">
              <a class="nav-link" href="#"><span>LAB MEMBERS</span></a>
          </li>
          <li class="nav-item">
              <a class="nav-link" href="#"><span>RESEARCH</span></a>
          </li>
          <li class="nav-item">
              <a class="nav-link" href="publications.html"><span>PUBLICATIONS</span></a>
          </li>
          <li class="nav-item">
              <a class="nav-link" href="#"><span>OPPORTUNITIES</span></a>
          </li>
      </ul>    
  </div>
</nav>

I am trying to find a way in JavaScript to detect whether the navbar is collapsed or expanded, so that I can style other elements on the page accordingly. The code snippet I attempted to use is as follows:

if ($('#toggle').attr('aria-expanded') == "true") {
  console.log("true")
  }

However, this code does not produce the desired outcome. Is there a more effective way to achieve this?

Answer №1

I gave it a try and it's functioning properly. It seems like you may be experiencing difficulties triggering the test or your toggle button might not have the required id (toggle).

Triggering the event (on click)

Track all clicks using:

window.onclick = function(e) { ... };

Alternative solution to your test

Just good old Vanilla JS:

if (!document.getElementById('toggle').classList.contains('collapsed')) {...}

Answer №2

Utilize the collapse events for your benefit:

$('#navbar').on('show.bs.collapse', function () {
    console.log('navbar is open');
}).on('hide.bs.collapse', function () {
    console.log('navbar is closed');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcbc4dbc4c3d0ecb8f3ebbcc3d3c6f3"></span></a>/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<nav id="navbar" class="navbar fixed-top navbar-expand-md navbar-light bg-light">
    <a class="navbar-brand" href="#"></a>
    <button id="toggle" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse text-right" id="navbarNav">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" id="about" href="Gibbs.html"><span><strong>ABOUT</strong></span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#"><span>NEWS</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#"><span>LAB MEMBERS</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#"><span>RESEARCH</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="publications.html"><span>PUBLICATIONS</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#"><span>OPPORTUNITIES</span></a>
            </li>
        </ul>
    </div>
</nav>

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

Having trouble displaying the collection data from firebase using React

I am having an issue retrieving a collection from firebase and then using a map function to loop through the documents and render some UI elements. The data is correctly logged in the console at line 20, however, the map function doesn't seem to be wo ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

Encountering build:web failure within npm script due to TypeScript

Our project is utilizing the expo-cli as a local dependency in order to execute build:web from an npm script without requiring the global installation of expo-cli. However, when we run npm run build:web, we encounter the following exception. To isolate th ...

Child components are not able to access properties from the root component in VUE3

Hi there! I'm currently learning VUE3 and had a question about defining global properties in the Root Component. I did some research on Google before posting this question, but couldn't find any relevant results. I would like to set a global pro ...

Employing an item as a function

My query pertains to utilizing an express application object (app object) as a callback function. The express application is known for its methods and properties that aid in handling HTTP requests. When integrating the app object with an HTTP server, it se ...

How to use React MUI Checkbox to set the checked value as false

I'm encountering an issue with the React MUI - Checkbox component. On my site, I have a checkbox linked to a handler that targets a REST API endpoint. This endpoint sets a boolean flag for the user in the database on a POST request and returns the boo ...

If you're not utilizing v-model.lazy, Vue3 Cleave js may encounter functionality issues

I am currently experimenting with cleavejs to format the thousand separator in my input numbers. I've noticed a strange behavior where if I input 1000.123, it displays as 1,000.12 which is the correct format. However, the v-model value remains as 1000 ...

CSS code completion in PhpStorm is not functioning properly for Twig extended templates

Currently, I am working with PhpStorm 2016.1 and facing an issue with file autocomplete. The scenario is as follows: @mycss .style {color : red} @base.html.twig [...] <link rel="stylesheet" href="/vendor/mycss.css" /> <!--HERE AUTOCOMPLETE OF s ...

How can users change the displayed Twitch channel?

My coding skills aren't the greatest, especially when it comes to something like this. I've tried searching for a solution with no luck, so I apologize if this is too basic or impossible. I have a simple page that loads up Twitch with a predefin ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

Adjust and position any svg element to fit the entire viewport

Forgive me for being just another person to ask this question. Despite my efforts, I have yet to find a solution. I am trying to resize "any" svg to fit the entire viewport, centered. Take for example this svg element: <svg baseProfile="full& ...

Submitting selected options from radio buttons to the server-side using HTML

I'm facing a challenge that requires some guidance. Here is the html code I am working with: Avatar: <br /> <input type="radio" id="avatar" name="avatar" value="Option1"/><img src="" alt=""> <input type="radio" id="avatar" name ...

Utilize the power of AJAX and Laravel to seamlessly upload an Excel file

I am currently facing an issue with importing an Excel file using AJAX and Laravel in my application. The form of excel import is embedded within another form and I have observed that the error handling is not displaying the error messages correctly on the ...

Using the npm timepicker in Laravel 5.8 with precision and efficiency

Looking for some guidance here as a newcomer to installing packages in Laravel. I'm currently working on implementing the timepicker feature from . In order to do this, I've already executed the command npm i jquery-timepicker. However, I seem t ...

Exploring object key-value pairs using the 'for in' loop in JavaScript

Embarking on a project to develop a quiz in javascript, I am starting with an array that holds the questions as anonymous objects. var allQuestions = [{ "question": "Who was Luke's wingman in the battle at Hoth?", "choices": ["Dak", "Biggs", "Wedge", ...

Determine the time left and check the speed of file uploads using ajax with jquery or javascript

Here is a snippet of code using jQuery.ajax to handle file uploads with progress tracking functionality. The function updates the DOM elements with information about bytes uploaded, total bytes, and percentage completed. However, I am looking for addition ...

Trouble in sending email with attachment using Microsoft Graph

I have been working on an application that has the functionality to send emails from a User, following the guidelines provided in this article. Despite everything else functioning correctly, I'm facing an issue when trying to include attachments. The ...

Executing jQuery on page update can be achieved by utilizing event handlers to trigger

I have implemented jQuery multi-select to enhance the user experience of my Django app's multiselect feature. Upon initially rendering my page, I included the following script to bind any elements with the class 'multiselect' to the jQuery m ...

Executing function statement

I'm currently learning about React hooks, and I have a question regarding the behavior of two function expressions within different useEffect hooks. In one case, the function expression named timerId in the first useEffect is invoked automatically wit ...

Is it possible to access the CSS property from an external CSS file even when inline styles are used?

Is there a way to retrieve the css property from an external source using JavaScript or jQuery even if inline styles are applied to the same element? Here's an example: <div id="my" style='left:100px'>some content</div> <styl ...