I'm using Twitter Bootstrap's navbar. While testing different screen resolutions, I noticed that on lower resolutions, sometimes the submenu would get cut off by the right side of the page.
In the code below, when a dropdown is opened, I'm getting the width of the dropdown menu and dropdown submenu, adding those together and checking them against the width of the window. If the width is greater than the window width, I add the class pull-right
so the dropdown menu and/or dropdown submenu will extend to the left and not get cut off by the right side of the page.
In this jsFiddle, you can see what I'm talking about by increasing/decreasing the width of the Results section. When you increase the width of the Results section far enough, the submenu for 'Dropdown 2' will open to the right. When you decrease the size of the Results section enough that the submenu would get cut off, the 'pull-right' class is applied and it extends to the left.
For the most part, this code is doing what it should, but does anyone have any suggestions on how to improve it?
JavaScript
$('.dropdown-toggle').click(function() {
var dropdownList = $('.dropdown-menu');
var dropdownOffset = $(this).offset();
var offsetLeft = dropdownOffset.left;
var dropdownWidth = dropdownList.width();
var docWidth = $(window).width();
var subDropdown = $('.dropdown-menu').eq(1);
var subDropdownWidth = subDropdown.width();
var isDropdownVisible = (offsetLeft + dropdownWidth <= docWidth);
var isSubDropdownVisible = (offsetLeft + dropdownWidth + subDropdownWidth <= docWidth);
if (!isDropdownVisible || !isSubDropdownVisible) {
$('.dropdown-menu').addClass('pull-right');
} else {
$('.dropdown-menu').removeClass('pull-right');
}
});
Please let me know if I need to better my explanation or if any other details are needed.