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

The function initFoodModel is missing and causing issues as it tries to read properties of undefined, specifically attempting to read 'findAll'

myWishlist.js const { setupFoodModel } = require("../../model/FoodModel"); const { setupWishlistModel } = require("../../model/myWishlistModel"); const setupMyWishlistModel = async () =\> { try { const sequelizeConnection = awai ...

Enhance the functionality of jQuery within a React application by creating custom chained jQuery functions

Before criticizing me, please hear me out: I understand that React can replace a majority of the functionalities provided by jQuery. However, I need specific interactions to occur when users hover over items, and as far as I know, React does not support th ...

Steps for displaying a pop-up window and showcasing a JSF Response

In my current project, I am utilizing JSF 1.2 without any component libraries for a JSF Application. One specific scenario I am tackling involves having a JSF-rendered page where clicking on a link should trigger the opening of a pop-up page displaying d ...

Aligning icons and text vertically in a list

I've encountered this issue multiple times and I'm always unsure of the best approach to resolve it. Here is a screenshot for better context: This is what it should look like... .container { max-width: 360px; font-size: 16px; } .talking-poin ...

Employ AJAX to dynamically refresh the page whenever a new row is inserted into the table

Currently, I am in the midst of learning AJAX because it is necessary for a project I am working on. The aim is to refresh a feed in real-time whenever a new row is added to a MYSQL table. While I have successfully achieved this using node.js, my client&ap ...

Is it possible to dynamically adjust the width of table columns using CSS/LESS on a per-column basis?

In this scenario, the table's column width is determined by the number of columns present. For example, if there are 4 columns in the table, each column's width would be set to a maximum of 25% of the table's overall width. With 3 columns, t ...

Jquery Ajax POST not functioning as expected

I have implemented a validation function on button click event using jQuery Ajax. This method displays an alert message if the return value is 1, otherwise it returns true and proceeds to the button method. The validation, alert display, and blocking of t ...

Can HTML tags be utilized in swipeable pages?

Currently, I am developing an Android app that incorporates swipe screen functionality. To achieve this, I followed a tutorial which can be found at the following link: http://developer.android.com/training/animation/screen-slide.html#fragment My goal is ...

Toggle switch with active state

I'm currently using Ionic 2 alongside Angular 2 beta 11. Is there a way to turn off the toggle switch? The Ionic documentation suggests using the checked attribute, but I've tried that and also attempted ng-checked with no luck. Any advice on t ...

ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields: id, requested_date, and location Additionally, there is another field called "date" which is located outside of the array. This "date" should always display th ...

Vue.js does not support using nested v-for loops with p tags

I'm facing an issue with nesting 2 v-for loops in Vue.js. It seems simple, but for some reason, it's not working as expected and I can't figure out why. Looping through the users and displaying their names works perfectly. Even extracting t ...

Tips for creating an expression within ng-if

I am struggling with placing an expression inside ng-if that needs to be assessed in order for my content to be shown based on its outcome. This is what I currently have: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image< ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

Unable to use NodeJS await/async within an object

I'm currently developing a validation module using nodeJs and I'm facing difficulties understanding why the async/await feature is not functioning correctly in my current module. Within this module, I need to have multiple exports for validation ...

Arrange two input fields side by side if the quantity of input fields is unspecified

I am currently in the process of developing a project using Angular. I have implemented an *ngFor loop to dynamically add input fields based on the data retrieved from the backend. Is there a way I can ensure that two input fields are displayed on the same ...

AngularJS parent selector nearest to the element

I have successfully implemented a code to close a custom popup using jQuery, but I am looking for a solution that utilizes AngularJS instead of jQuery. Can anyone assist me in finding the equivalent of this.closest() in AngularJS? I aim to hide .popOverla ...

Converting Callbacks to Promises in Node.js

I am facing a challenge with my node js application as I am attempting to promisify multiple callback functions without success. It has reached a point where I am unsure if it is even feasible. If you can assist me in promisifying the code provided below, ...

Retrieving the background image URL from inline CSS using jQuery

I'm looking for a link similar to url(img/bg/06.jpg), but when using jQuery, I get a longer link like url("file:///D:/WORKING%20FILE/One%20Landing%20Page/version/img/bg/06.jpg") https://i.stack.imgur.com/8WKgv.png Below is the code snippet in questi ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

Adjust the width of a container as its children expand

My current project involves creating a dynamic gallery using JavaScript and jQuery, where full-sized images slide out from the right side. I have successfully implemented this functionality, but now I am facing a new challenge. I need the parent block of t ...