Home > Blockchain >  How do you trigger the on collapse event on a bootstrap navbar?
How do you trigger the on collapse event on a bootstrap navbar?

Time:12-20

This question is most likely a repeat, but I can't seem to find the answer on any other related one. When the navbar collapses on smaller screens, how do you trigger an event signaling that the collapse button icon has been clicked? I have tried using the following js code below to no avail:

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

Or this:

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

This is my code so far:

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


<nav  id='my-nav' >
            <div >
                <a  href="/">
                    <img src="" alt="logo" width="40" height="40" id="logo"/>
                </a>
                <button  type="button" data-bs-toggle="collapse" data-bs-target="#main_nav">
                    <span className="navbar-toggler-icon" id="toggler"></span>
                </button>
                <div  id="main_nav">
                    
                </div> 
            </div> 
        </nav>

Which class/id should I reference in the jquery event listener in order to invoke the event the happens when the collapse button is clicked on smaller screens?

CodePudding user response:

For the events in Bootstrap to work properly, be sure to enter jQuery and boostrap.js in the head.

<link href="https://cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

Then in the case of events, the event must be fired on the parent element with the .navbar class.

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

Also modify your html code to the form below


<nav  id='my-nav'>
  <div >
    <a  href="/">
    <img src="" alt="logo"/>
    </a>
    <button  type="button" data-bs-toggle="collapse" data-bs-target="#main_nav">
      <span ></span>
    </button>
    <div  id="main_nav">
    
    </div>
    </div>
</nav>

CodePudding user response:

Due to I'm a little confused that Original Poster asked about trigger the event but what he trying to do is listen the event (from the code).

So, I'll try to solve both.

The OP's HTML did not showing any contents in the navbar menu. I'll use an example from Bootstrap document instead.

<nav >
  <div >
    <a  href="#">Navbar</a>
    <button  type="button" data-bs-toggle="collapse" data-bs-target="#main_nav" aria-controls="main_nav" aria-expanded="false" aria-label="Toggle navigation">
      <span ></span>
    </button>
    <div  id="main_nav">
      <ul >
        <li >
          <a  aria-current="page" href="#">Home</a>
        </li>
        <li >
          <a  href="#">Link</a>
        </li>
        <li >
          <a  href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Dropdown
          </a>
          <ul  aria-labelledby="navbarDropdown">
            <li><a  href="#">Action</a></li>
            <li><a  href="#">Another action</a></li>
            <li><hr ></li>
            <li><a  href="#">Something else here</a></li>
          </ul>
        </li>
        <li >
          <a >Disabled</a>
        </li>
      </ul>
      <form >
        <input  type="search" placeholder="Search" aria-label="Search">
        <button  type="submit">Search</button>
      </form>
    </div>
  </div>
</nav>


<p>
    Custom buttons
    <button id="trigger">
    collapse/expand.
    </button>
    <button id="triggerexpand">
    expand.
    </button>
    <button id="triggercollapse">
    collapse.
    </button>
</p>
$('#main_nav').on('hide.bs.collapse', function() {
    console.log('on collapsing')
});
$('#main_nav').on('hidden.bs.collapse', function() {
    console.log('collapsed')
});


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


$('#trigger').on('click', (e) => {
    e.preventDefault();
    console.log('trigering');
    const event1 = new CustomEvent('hide.bs.collapse', { bubbles: true});
    const event2 = new CustomEvent('hidden.bs.collapse', { bubbles: true});

    let thisButton = e.target;
    // use dispatchEvent() (not working).
    $('#main_nav')[0].dispatchEvent(event1);// not working.
    $('#main_nav')[0].dispatchEvent(event2);// not working.
    // try to dispatch event on root document (not working).
    document.dispatchEvent(event1);// not working.
    document.dispatchEvent(event2);// not working.

    // use jQuery.trigger() (not working).
    $('#main_nav').trigger('hide.bx.collapse');// not working.
    $('#main_nav').trigger('hidden.bx.collapse');// not working.

    // do jQuery trigger "click". (collapse/expand WORK).
    $('.navbar-toggler').trigger('click');
});

$('#triggerexpand').on('click', (e) => {
    e.preventDefault();
    // trigger to expand only.
    let myCollapse = document.getElementById('main_nav');
    let bsCollapse = new bootstrap.Collapse(myCollapse, {
      toggle: false
    });
    bsCollapse.show();
});

$('#triggercollapse').on('click', (e) => {
    e.preventDefault();
    // trigger to collapse only.
    let myCollapse = document.getElementById('main_nav');
    let bsCollapse = new bootstrap.Collapse(myCollapse, {
      toggle: false
    });
    bsCollapse.hide();
});

In my code above, I listen all 4 events on navbar. You can use any selector (#main_nav, or .navbar-collapse).
The event listener you are using is already correct, in case that you want to listen the events and not working it is come from your incorrect HTML.

I added the trigger button to do trigger event as in your question. Please notice again that trigger event is NOT the same as listen event.
To trigger event, you can't just use .dispatchEvent() or .trigger() with event name. That is not working with Bootstrap collapse events.
To make trigger event works, you have to trigger click instead. Using .trigger('click') will tells jQuery to do click on that button and navbar will be collapse/expand, the events will be fired.

See it in jsfiddle 1, 2.

  • Related