[javascript] Adding a slide effect to bootstrap dropdown

I'm using bootstrap, and I'd like to add animation to a dropdown. I want to add an animation to it, slide down and back up when leaving it. How could I do this?

Things I tried:

Changing the Js drop down file like this:

How can I make Bootstrap's navigation dropdown slide smoothly up and down?

This question is related to javascript drop-down-menu twitter-bootstrap

The answer is


For Bootstrap 3, this variation on the answers above makes the mobile slideUp() animation smoother; the answers above have choppy animation because Bootstrap removes the .open class from the toggle's parent immediately, so this code restores the class until the slideUp() animation is finished.

// Add animations to topnav dropdowns
// based on https://stackoverflow.com/a/19339162
// and https://stackoverflow.com/a/52231970

$('.dropdown')
  .on('show.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
  })
  .on('hide.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, false).slideUp(300, function() {
      $(this).parent().removeClass('open');
    });
  })
  .on('hidden.bs.dropdown', function() {
    $(this).addClass('open');
  });

Key differences:

  • In the hide.bs.dropdown event handler I'm using .stop()'s default value (false) for its second argument (jumpToEnd)
  • The hidden.bs.dropdown event handler restores the .open class to the dropdown toggle's parent, and it does this pretty much immediately after the class has been first removed. Meanwhile the slideUp() animation is still running, and just like in the answers above, its "the-animation-is-completed" callback is responsible for finally removing the .open class from its parent.
  • Methods are chained together because the selector for each event handler is the same

Here is a nice simple solution using jQuery that works nicely:

$('.dropdown-toggle').click(function () {
    $(this).next('.dropdown-menu').slideToggle(300);
});

$('.dropdown-toggle').focusout(function () {
    $(this).next('.dropdown-menu').slideUp(300);
})

The slide animation toggle occurs on clicking and it always slides back up on losing focus.

Alter the 300 value to anything you want, the lower the number the faster the animation.

Edit:

This solution will only work for desktop views. It will need some further modification in order to display nicely for mobile.


here is my solution for slide & fade effect:

   // Add slideup & fadein animation to dropdown
   $('.dropdown').on('show.bs.dropdown', function(e){
      var $dropdown = $(this).find('.dropdown-menu');
      var orig_margin_top = parseInt($dropdown.css('margin-top'));
      $dropdown.css({'margin-top': (orig_margin_top + 10) + 'px', opacity: 0}).animate({'margin-top': orig_margin_top + 'px', opacity: 1}, 300, function(){
         $(this).css({'margin-top':''});
      });
   });
   // Add slidedown & fadeout animation to dropdown
   $('.dropdown').on('hide.bs.dropdown', function(e){
      var $dropdown = $(this).find('.dropdown-menu');
      var orig_margin_top = parseInt($dropdown.css('margin-top'));
      $dropdown.css({'margin-top': orig_margin_top + 'px', opacity: 1, display: 'block'}).animate({'margin-top': (orig_margin_top + 10) + 'px', opacity: 0}, 300, function(){
         $(this).css({'margin-top':'', display:''});
      });
   });

$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
}, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});

This code works if you want to reveal dropdowns on hover.

I just changed the .slideToggle to .slideDown & .slideUp, and removed the (400) timing


On click it can be done using below code

$('.dropdown-toggle').click(function() {
  $(this).next('.dropdown-menu').slideToggle(500);
});

BOOTSTRAP 3 REFERENCE

Added because I keep getting caught by the solution in this thread and it stuffs me up every time.

Basically the BS dropdown immediately removes the .open class from the parent, so sliding up does not work.

Use the same bit as other solutions for slideDown();

// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.dropdown').on('hide.bs.dropdown', function(e){
  e.preventDefault();
  $(this).find('.dropdown-menu').first().stop(true, true).slideUp(300, function(){
    $(this).parent().removeClass('open');
  });
});

Expanded answer, was my first answer so excuse if there wasn’t enough detail before.

For Bootstrap 3.x I personally prefer CSS animations and I've been using animate.css & along with the Bootstrap Dropdown Javascript Hooks. Although it might not have the exactly effect you're after it's a pretty flexible approach.

Step 1: Add animate.css to your page with the head tags:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css">

Step 2: Use the standard Bootstrap HTML on the trigger:

<div class="dropdown">
  <button type="button" data-toggle="dropdown">Dropdown trigger</button>

  <ul class="dropdown-menu">
    ...
  </ul>
</div>

Step 3: Then add 2 custom data attributes to the dropdrop-menu element; data-dropdown-in for the in animation and data-dropdown-out for the out animation. These can be any animate.css effects like fadeIn or fadeOut

<ul class="dropdown-menu" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
......
</ul>

Step 4: Next add the following Javascript to read the data-dropdown-in/out data attributes and react to the Bootstrap Javascript API hooks/events (http://getbootstrap.com/javascript/#dropdowns-events):

var dropdownSelectors = $('.dropdown, .dropup');

// Custom function to read dropdown data
// =========================
function dropdownEffectData(target) {
  // @todo - page level global?
  var effectInDefault = null,
      effectOutDefault = null;
  var dropdown = $(target),
      dropdownMenu = $('.dropdown-menu', target);
  var parentUl = dropdown.parents('ul.nav'); 

  // If parent is ul.nav allow global effect settings
  if (parentUl.size() > 0) {
    effectInDefault = parentUl.data('dropdown-in') || null;
    effectOutDefault = parentUl.data('dropdown-out') || null;
  }

  return {
    target:       target,
    dropdown:     dropdown,
    dropdownMenu: dropdownMenu,
    effectIn:     dropdownMenu.data('dropdown-in') || effectInDefault,
    effectOut:    dropdownMenu.data('dropdown-out') || effectOutDefault,  
  };
}

// Custom function to start effect (in or out)
// =========================
function dropdownEffectStart(data, effectToStart) {
  if (effectToStart) {
    data.dropdown.addClass('dropdown-animating');
    data.dropdownMenu.addClass('animated');
    data.dropdownMenu.addClass(effectToStart);    
  }
}

// Custom function to read when animation is over
// =========================
function dropdownEffectEnd(data, callbackFunc) {
  var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
  data.dropdown.one(animationEnd, function() {
    data.dropdown.removeClass('dropdown-animating');
    data.dropdownMenu.removeClass('animated');
    data.dropdownMenu.removeClass(data.effectIn);
    data.dropdownMenu.removeClass(data.effectOut);

    // Custom callback option, used to remove open class in out effect
    if(typeof callbackFunc == 'function'){
      callbackFunc();
    }
  });
}

// Bootstrap API hooks
// =========================
dropdownSelectors.on({
  "show.bs.dropdown": function () {
    // On show, start in effect
    var dropdown = dropdownEffectData(this);
    dropdownEffectStart(dropdown, dropdown.effectIn);
  },
  "shown.bs.dropdown": function () {
    // On shown, remove in effect once complete
    var dropdown = dropdownEffectData(this);
    if (dropdown.effectIn && dropdown.effectOut) {
      dropdownEffectEnd(dropdown, function() {}); 
    }
  },  
  "hide.bs.dropdown":  function(e) {
    // On hide, start out effect
    var dropdown = dropdownEffectData(this);
    if (dropdown.effectOut) {
      e.preventDefault();   
      dropdownEffectStart(dropdown, dropdown.effectOut);   
      dropdownEffectEnd(dropdown, function() {
        dropdown.dropdown.removeClass('open');
      }); 
    }    
  }, 
});

Step 5 (optional): If you want to speed up or alter the animation you can do so with CSS like the following:

.dropdown-menu.animated {
  /* Speed up animations */
  -webkit-animation-duration: 0.55s;
  animation-duration: 0.55s;
  -webkit-animation-timing-function: ease;
  animation-timing-function: ease;
}

Wrote an article with more detail and a download if anyones interested: article: http://bootbites.com/tutorials/bootstrap-dropdown-effects-animatecss

Hope that’s helpful & this second write up has the level of detail that’s needed Tom


Intro

As of the time of writing, the original answer is now 8 years old. Still I feel like there isn't yet a proper solution to the original question.

Bootstrap has gone a long way since then and is now at 4.5.2. This answer addresses this very version.

The problem with all other solutions so far

The issue with all the other answers is, that while they hook into show.bs.dropdown / hide.bs.dropdown, the follow-up events shown.bs.dropdown / hidden.bs.dropdown are either fired too early (animation still ongoing) or they don't fire at all because they were suppressed (e.preventDefault()).

A clean solution

Since the implementation of show() and hide() in Bootstraps Dropdown class share some similarities, I've grouped them together in toggleDropdownWithAnimation() when mimicing the original behaviour and added little QoL helper functions to showDropdownWithAnimation() and hideDropdownWithAnimation().
toggleDropdownWithAnimation() creates a shown.bs.dropdown / hidden.bs.dropdown event the same way Bootstrap does it. This event is then fired after the animation completed - just like you would expect.

/**
 * Toggle visibility of a dropdown with slideDown / slideUp animation.
 * @param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
 * @param {boolean} show Show (true) or hide (false) the dropdown menu.
 * @param {number} duration Duration of the animation in milliseconds
 */
function toggleDropdownWithAnimation($containerElement, show, duration = 300): void {
    // get the element that triggered the initial event
    const $toggleElement = $containerElement.find('.dropdown-toggle');
    // get the associated menu
    const $dropdownMenu = $containerElement.find('.dropdown-menu');
    // build jquery event for when the element has been completely shown
    const eventArgs = {relatedTarget: $toggleElement};
    const eventType = show ? 'shown' : 'hidden';
    const eventName = `${eventType}.bs.dropdown`;
    const jQueryEvent = $.Event(eventName, eventArgs);

    if (show) {
        // mimic bootstraps element manipulation
        $containerElement.addClass('show');
        $dropdownMenu.addClass('show');
        $toggleElement.attr('aria-expanded', 'true');
        // put focus on initial trigger element
        $toggleElement.trigger('focus');
        // start intended animation
        $dropdownMenu
            .stop() // stop any ongoing animation
            .hide() // hide element to fix initial state of element for slide down animation
            .slideDown(duration, () => {
            // fire 'shown' event
            $($toggleElement).trigger(jQueryEvent);
        });
    }
    else {
        // mimic bootstraps element manipulation
        $containerElement.removeClass('show');
        $dropdownMenu.removeClass('show');
        $toggleElement.attr('aria-expanded', 'false');
        // start intended animation
        $dropdownMenu
            .stop() // stop any ongoing animation
            .show() // show element to fix initial state of element for slide up animation
            .slideUp(duration, () => {

            // fire 'hidden' event
            $($toggleElement).trigger(jQueryEvent);
        });
    }
}

/**
 * Show a dropdown with slideDown animation.
 * @param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
 * @param {number} duration Duration of the animation in milliseconds
 */
function showDropdownWithAnimation($containerElement, duration = 300) {
    toggleDropdownWithAnimation($containerElement, true, duration);
}

/**
 * Hide a dropdown with a slideUp animation.
 * @param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
 * @param {number} duration Duration of the animation in milliseconds
 */
function hideDropdownWithAnimation($containerElement, duration = 300) {
    toggleDropdownWithAnimation($containerElement, false, duration);
}

Bind Event Listeners

Now that we have written proper callbacks for showing / hiding a dropdown with an animation, let's actually bind these to the correct events.

A common mistake I've seen a lot in other answers is binding event listeners to elements directly. While this works fine for DOM elements present at the time the event listener is registered, it does not bind to elements added later on.

That's why you are generally better off binding directly to the document:

$(function () {

    /* Hook into the show event of a bootstrap dropdown */
    $(document).on('show.bs.dropdown', '.dropdown', function (e) {
        // prevent bootstrap from executing their event listener
        e.preventDefault();
        
        showDropdownWithAnimation($(this));
    });

    /* Hook into the hide event of a bootstrap dropdown */
    $(document).on('hide.bs.dropdown', '.dropdown', function (e) {
        // prevent bootstrap from executing their event listener
        e.preventDefault();
          
        hideDropdownWithAnimation($(this));
    });

});

I don't know if I can bump this thread, but I figured out a quick fix for the visual bug that happens when the open class is removed too fast. Basically, all there is to it is to add an OnComplete function inside the slideUp event and reset all active classes and attributes. Goes something like this:

Here is the result: Bootply example

Javascript/Jquery:

$(function(){
    // ADD SLIDEDOWN ANIMATION TO DROPDOWN //
    $('.dropdown').on('show.bs.dropdown', function(e){
        $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
    });

    // ADD SLIDEUP ANIMATION TO DROPDOWN //
    $('.dropdown').on('hide.bs.dropdown', function(e){
        e.preventDefault();
        $(this).find('.dropdown-menu').first().stop(true, true).slideUp(400, function(){
            //On Complete, we reset all active dropdown classes and attributes
            //This fixes the visual bug associated with the open class being removed too fast
            $('.dropdown').removeClass('show');
            $('.dropdown-menu').removeClass('show');
            $('.dropdown').find('.dropdown-toggle').attr('aria-expanded','false');
        });
    });
});

I'm doing something like that but on hover instead of on click.. This is the code I'm using, you might be able to tweak it up a bit to get it to work on click

$('.navbar .dropdown').hover(function() {
  $(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
  $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp()
});

Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:

.dropdown .dropdown-menu {
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;

    max-height: 0;
    display: block;
    overflow: hidden;
    opacity: 0;
}

.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
    max-height: 300px;
    opacity: 1;
}

The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.

It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.

Here is small example: DEMO


! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.


Update 2018 Bootstrap 4

In Boostrap 4, the .open class has been replaced with .show. I wanted to implement this using only CSS transistions without the need for extra JS or jQuery...

.show > .dropdown-menu {
  max-height: 900px;
  visibility: visible;
}

.dropdown-menu {
  display: block;
  max-height: 0;
  visibility: hidden;
  transition: all 0.5s ease-in-out;
  overflow: hidden;
}

Demo: https://www.codeply.com/go/3i8LzYVfMF

Note: max-height can be set to any large value that's enough to accommodate the dropdown content.


I am using the code above but I have changed the delay effect by slideToggle.

It slides the dropdown on hover with animation.

$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400);
    }, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400)
    });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation