Determine whether the drop-down menu on the network will be displayed from the screen

I have a simple CSS based drop down menu with several levels. The second or third level may go beyond the visible window with certain combinations of resolution and window size.

Some ready-made menu items simply open the drop-down menu to the left, rather than the right, if they detect this situation.

How can I check (with JS / jQuery) for this situation?

+4
source share
3 answers

You can check if a menu item is turned off with the following function:

/*--- function bIsNodeClippedOrOffscreen returns true if a node is offscreen (without scrolling). Requires jQuery. */ function bIsNodeClippedOrOffscreen (zJnode) { var aDivPos = zJnode.offset (); var iLeftPos = aDivPos.left; var iTopPos = aDivPos.top; var iDivWidth = zJnode.outerWidth (true); var iDivHeight = zJnode.outerHeight (true); var bOffScreen = CheckIfPointIsOffScreen (iLeftPos, iTopPos); var bClipped = CheckIfPointIsOffScreen (iLeftPos + iDivWidth, iTopPos + iDivHeight); return (bOffScreen || bClipped); } function CheckIfPointIsOffScreen (iLeftPos, iTopPos) { var iBrowserWidth = $(window).width() - 16; //-- 16 is fudge for scrollbars, refine later var iBrowserHeight = $(window).height() - 16; //-- 16 is fudge for scrollbars, refine later var bOffScreen = false; if (iLeftPos < 0 || iLeftPos >= iBrowserWidth) bOffScreen = true; if (iTopPos < 0 || iTopPos >= iBrowserHeight) bOffScreen = true; return bOffScreen; } 

.
Using an example:

 <li id="SomeMenuItem"> Get your shopping cart for free! ... ... var Node = $("#SomeMenuItem"); var NeedToMoveIt = bIsNodeClippedOrOffscreen (Node); 
+2
source

You must display the item to get the size in order to display submenus from the screen. Get the width / height of the element, calculate the expected display position (right / bottom), compare with the width / height of the screen, determine which location to display and move the element to the end position.

(unverified example)

 function displaysOffPageRight(defaultLeft){ $('#submenu1').addClass('displayOffScreen'); var offPage = defaultLeft + $('#submenu1').width() > screen.width; $('#submenu1').removeClass('displayOffScreen'); return offPage; } 
+1
source

When the menu is not yet displayed, you cannot get its size. establish your position. If you set visibility: hidden CSS visibility: hidden and display: none , the menu will not be displayed, but its size will be determined. Then you can jQuery.offset its position using jQuery.offset and its height / width using jQuery.outerWidth/outerHeight (note the margin options for the latest functions). Yes, and be careful if you use any negative fields, this will require special handling.

Get the window dimensions using jQuery(window).height() and .width() and you can understand the math from there.

+1
source

Source: https://habr.com/ru/post/1313422/


All Articles