coder coder - 1 year ago 278
Javascript Question

Bootstrap dropdown list position (Up/Bottom) based on document height

I have bootstrap dropmenu list on my page. When page is minimized or screen is adjusted, the menulist is going off the screen. I want to check and display them in upwards if screen height is making the list going off the screen.

here is my html,

<div class="btn-group pull-right">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Click<span class="caret"></span></button>
<ul class="dropdown-menu pull-right" role="menu">

Note: List is going off in respective to height, not width. Width of the screen doesn't matter because i am already using "pull-right" which makes my list display inside the screen.

Answer Source

To cause a dropdown menu to instead display upwards when its toggle control is clicked, you should use the .dropup class on the menu's container element. To determine when to apply this class, you can calculate whether the bottom of the expanded dropdown will end up below the window, and if it does, apply the .dropup class.

One possible implementation of this (attached to the window's scroll event):

function determineDropDirection(){
  $(".dropdown-menu").each( function(){

    // Invisibly expand the dropdown menu so its true height can be calculated
      visibility: "hidden",
      display: "block"

    // Necessary to remove class each time so we don't unwantedly use dropup's offset top

    // Determine whether bottom of menu will be below window at current scroll position
    if ($(this).offset().top + $(this).outerHeight() > $(window).innerHeight() + $(window).scrollTop()){

    // Return dropdown menu to fully hidden state



Here's a Bootply to demonstrate. Try making the demo panel shorter, and then scroll the panel up and down to see how the dropdown menu will appear above/below its toggle control depending on the available space it has.

Hope this helps! Let me know if you have any questions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download