I'm working on a project over at github pages, which I replace a bootstrap `.dropdown` with `.dropup` if the div's `overflow-y: scroll` will cause the dropdown menu to be cutoff / overflow. You can see the function working properly at this [jsfiddle](https://jsfiddle.net/qb9dhfk0/5/). Notice if you click on the ellipsis icon to the right on the top rows, it will drop down, if you click on the icon on the bottom rows, it will drop up. 

Now, my actual implementation ([github page](https://kmodoio.github.io/wavesurfer-player.js/)), the code is exactly the same (below), but it wants to replace all `.dropdown` classes with `.dropup` when opened, including the top-most row which gets cut off, seen in the photo below. 
[![enter image description here](https://i.stack.imgur.com/Cq7MB.png)](https://i.stack.imgur.com/Cq7MB.png)
I've been struggling with this for a week and can't quite figure it out. I've tried a few different things that I thought fixed it but ended up just being a hack and didn't work on mobile, or replaced some but not all etc. 

Here is the Javascript / jQuery I'm using, which can be seen in the jsfiddle and my github source [here](https://github.com/kmodoio/wavesurfer-player.js/blob/master/docs/js/wavesurfer-player.js).

```
$(document).on("shown.bs.dropdown", ".dropdown", function () {
  // calculate the required sizes, spaces
  var $ul = $(this).children(".dropdown-menu");
  var $button = $(this).children(".song-menu");
  var ulOffset = $ul.offset();
  // how much space would be left on the top if the dropdown opened that direction
  var spaceUp = (ulOffset.top - $button.height() - $ul.height()) - $('#playlist').scrollTop();
  // how much space is left at the bottom
  var spaceDown = $('#playlist').scrollTop() + $('#playlist').height() - ((ulOffset.top + 10) + $ul.height());
  // switch to dropup only if there is no space at the bottom AND there is space at the top, or there isn't either but it would be still better fit
  if (spaceDown < 0 && (spaceUp >= 0 || spaceUp > spaceDown))
    $(this).addClass("dropup");
}).on("hidden.bs.dropdown", ".dropdown", function() {
  // always reset after close
  $(this).removeClass("dropup");
});

```

**Edit:** 
To clear up any confusion, here's an example of the behavior without my added `.dropup` function. [jsfiddle](https://jsfiddle.net/qb9dhfk0/6/) Notice when you click the last menu item, it opens the menu but requires scrolling. I specifically want to remove the `.dropdown` class and add `.dropup` in this case, so no scrolling is required.