joshmoto
joshmoto

Reputation: 5088

toggle body class when navbar collapse show class is added/removed

The are many ways to do this, but I want the best and cleanest method.

I want to toggle a custom body class when the .navbar-toggle toggles the .show class on the .navbar-collapse element.

I just think using another on click event on something that is already firing javascript seems a bit dirty. Is there anyway to bind to the existing functionally?

<body class="">
  <nav class="navbar navbar-dark bg-dark">
    <a class="navbar-brand" href="#">#</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="navbar-collapse collapse" id="navbarCollapse">
      <ul class="navbar-nav mr-auto">
        ...
      </ul>
    </div>
  </nav>
</body>

https://jsfiddle.net/joshmoto/s74x32uf/

Any ideas would be great thanks

Upvotes: 1

Views: 1298

Answers (1)

VVV
VVV

Reputation: 7593

The best way is to use Bootstrap's collapse events

When the open animation is finished

$('.navbar').on('shown.bs.collapse', function () {
  alert('animation complete');
  $('body').addClass('your-class');
})

When the closed animation is finished

$('.navbar').on('hidden.bs.collapse', function () {
  alert('animation complete');
  $('body').addClass('your-class');
})

You can also add an event when the animation starts showing/hiding by using show.bs.collapse or hide.bs.collapse

Updated fiddle

Upvotes: 2

Related Questions