What is the method for activating the on collapse event with a bootstrap navbar?

I am encountering a common issue with collapsing the navbar on smaller screens and triggering an event when the collapse button icon is clicked. Despite my efforts to find a solution, I have been unsuccessful in using the following JavaScript code:

$('#main_nav').on('hidden.bs.collapse', function () {
        alert('collapse')
 })

Additionally, I tried this approach:

$('.navbar-collapse').on('show.bs.collapse', function () {
        console.log("collapse");
});

Here is the current state of my code:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<nav class="autohide navbar navbar-expand-lg navbar-dark" id='my-nav' >
            <div class="container-fluid">
                <a class="navbar-brand" href="/">
                    <img src="" alt="logo" width="40" height="40" id="logo"/>
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main_nav">
                    <span className="navbar-toggler-icon" id="toggler"></span>
                </button>
                <div class="collapse navbar-collapse text-color" id="main_nav">
                    
                </div> 
            </div> 
        </nav>

Could you please advise me on which class/id I should use in the jQuery event listener to properly handle the collapse button click event on smaller screens?

Answer №1

I am a bit puzzled because the Original Poster inquired about triggering an event, but it seems like they actually want to listen for the event (based on the code).

Therefore, I will attempt to address both scenarios.

The OP's HTML does not display any content in the navbar menu. Instead, I will use an example from the Bootstrap documentation.

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main_nav" aria-controls="main_nav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="main_nav">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        [Rest of the HTML code...]
[JS Event Listeners...]

In my provided code, I have set up event listeners for all 4 events on the navbar. You can utilize any selector (#main_nav, or .navbar-collapse).
The event listener you are using is correct, assuming you wish to listen for the events. If it's not working, there might be an issue with your HTML implementation.

I included trigger buttons to demonstrate how to trigger events as mentioned in your question. It is important to differentiate between triggering and listening events.
To successfully trigger an event, simply calling .dispatchEvent() or .trigger() with the event name may not work with Bootstrap collapse events.
For successful event triggering, you should simulate a click instead. Utilizing .trigger('click') prompts jQuery to perform a click action on that button, causing the navbar to collapse/expand and the associated events to fire.

You can see this in action on jsfiddle 1 and 2.

Answer №2

To ensure that Bootstrap events function correctly, make sure to include jQuery and bootstrap.js in the head section of your HTML document.

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37555858434443455647770219071905">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9994948f888f899a8bbbced5cbd5c9">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

When triggering events, remember that the event should be triggered on the parent element with the .navbar class.

$('.navbar').on('show.bs.collapse', function () {
        console.log("collapse");
});

Additionally, update your HTML code to match the following format:


<nav class="navbar navbar-expand-lg navbar-light bg-light" id='my-nav'>
  <div class="container-fluid">
    <a class="navbar-brand" href="/">
    <img src="" alt="logo"/>
    </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main_nav">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse text-color" id="main_nav">
    
    </div>
    </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

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

Using CSS :active can prevent the click event from firing

I've designed a navigation menu that triggers a jquery dialog box to open when a link is clicked. My CSS styling for the links includes: .navigationLinkButton:active { background:rgb(200,200,200); } To attach the dialog box, I simply use: $("#l ...

Exploring the Power of Asynchronous Operations with Await and Async in

I have a basic understanding of how to use await/async in Angular 2 with the following example: async getValueWithAsync() { const value = <number>await this.resolveAfter2Seconds(20); console.log(`async result: ${value}`); } In my Angular ...

Exploring AngularJS tab navigation and injecting modules into the system

Two separate modules are defined in first.js and second.js respectively: first.js var app = angular.module('first',['ngGrid']); app.controller('firstTest',function($scope)) { ... }); second.js var app = angular.mo ...

I often struggle with creating social media buttons using Material UI

Unfortunately, the code provided is not rendering social media icons or buttons as expected. In the initial lines, material UI icons/buttons were imported from the React Material UI library (IconButton / AlarmIcon). import './App.css'; impor ...

Searching through an array to isolate only image files

I am working with an array that contains various file types, all stored under the property array.contentType. I am trying to filter out just the images using array.contentType.images, I believe. Check out the code snippet below: const renderSlides = a ...

Customizing valueAxis dynamically in Amcharts

I am currently utilizing Amcharts to display my data. Within my chart, I have 4 graphs with valueAxes ranging from 0 to 100. Is there a method for me to dynamically change the valueAxes to a range of 0-250 after the chart has been loaded in the view? I ...

What is the best way to fulfill a promise after a CSV file has finished being read?

I have been utilizing the 'fast-csv' module that can be found at this link (https://www.npmjs.org/package/fast-csv), but I am open to switching to a different one. I attempted promised-csv (https://www.npmjs.org/package/promised-csv) but I had tr ...

Rows in the table are not extending to their full length

I'm having an issue with my Bootstrap table design. I have 8 header cells and 5 body cells, but the rows are only stretching across 4 columns. I've hit a blank trying to figure out why. <script src="https://cdnjs.cloudflare.com/ajax/libs/jq ...

The functionality of Jquery appears to be malfunctioning on the Drupal platform, although it performs

I've built a jQuery carousel that is fully functional when tested locally, but encounters issues when uploaded to a Drupal platform. Surprisingly, the jQuery functions properly when entered through the Console. Here's the jQuery code: carousel = ...

Transforming XML data into HTML format

This XML Data needs to be converted <xml> <0> <id>e1</id> <Product name>vivo Y11s 4G Smartphone, 32GB, 6.51 HD Display Phantom Black</Product name> <Price>197</Price> <Wireless carrier> ...

Unable to customize the button color within the Bootstrap framework

This button was created using Bootstrap. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <lin ...

Verify the value of the variable matches the key of the JavaScript object array and retrieve the corresponding value

array = { event: [{ key: "value", lbl: "value" }], event1: [{ key: "value", lbl: "value" }] var variable; if(variable in array){ //need to handle this case } I am looking for a function that takes the name of an ar ...

Enhancing Jquery UI tabs with personalized designs

I am having trouble adding custom styles to my jQuery UI tabs. I have a specific design in mind for how the tabs should look. Unfortunately, I haven't been able to figure it out yet despite my efforts. Here is the code I currently have: <div id= ...

Is there a way to use JavaScript to modify the position of a div element

Can we adjust the div position using CSS (absolute or relative) with JavaScript? Here's an example code snippet: <div id="podpis" style="margin-top: 2rem;"> <div class="invoice-signature"> <span><?=$xml->sanitiz ...

Changing the way in which text is selected and copied from a webpage with visible white space modifications

After working on developing an HTML parser and formatter, I have implemented a new feature that allows whitespace to be rendered visible by replacing spaces with middle dot (·) characters and adding arrows for tabs and newlines. You can find the current ...

Optimal method for a React and HTML Select-component to output String values instead of Integer values

Within my React-class (JSX), I've included the following code: var Select = React.createClass({ onChange: function (ev) { console.log(ev.target.value); }, render: function() { var optionsHtml = this.state.options.map(function (el) { ...

Tips for overlapping children in a column flex direction while maintaining the parents' positioning

Currently, I am working with two parent flex items, arranged with flex-direction: column. Within the first parent, there are two children. However, one of the children is optional and may be removed at times. I aim to have the optional child displayed on ...

What are the steps to display a graph on a webpage using AJAX in Django?

I'm currently working on developing a weather forecast application, and I have implemented a date input box on the home page. When users enter a date and click submit, a graph displaying temperature data should be displayed. I have set up a URL that r ...

updating the state value through an onChange event in the input field requires taking action by clicking outside the field

I've hit a roadblock trying to figure out how to update my button in real-time. Despite scouring various forums and threads for solutions (React form onChange->setState one step behind), I haven't been successful in resolving the issue within ...