Last active
March 5, 2019 20:40
-
-
Save davidsword/12ca4e09dff1658beec7e5728cbc10d0 to your computer and use it in GitHub Desktop.
JS - Move a dropdown menu that's overflowing out off viewport back into view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If the sub-navigation is off-screen we want to bump it left. | |
const parentsli = document.querySelectorAll( 'ul > li.page_item_has_children' ); | |
for ( let parent of parentsli ) { | |
const children = parent.querySelector( 'ul.children' ); | |
parent.addEventListener( 'mouseenter', evt => { | |
// Compare with width, to dropdown offset, to width of drop down. | |
const windowWidth = document.documentElement.clientWidth; | |
// If mobile, don't bother. | |
if (windowWidth < 1000) return; | |
const dropDownRect = children.getBoundingClientRect(); | |
const dropDownLeft = dropDownRect.left; | |
const dropDownWidth = 320; | |
// If it's offscreen, fix it. | |
const offscreen = ( windowWidth < ( dropDownLeft + dropDownWidth ) ); | |
if ( offscreen ) { | |
const offset = ( dropDownLeft + dropDownWidth ) - windowWidth; | |
children.style.transform = `translateX(-${offset}px)`; | |
} | |
}); | |
// Reset when we mouse out, so if a user resizes window, the math starts from scratch. | |
parent.addEventListener( 'mouseleave', evt => { | |
children.style.transform = 'translateX(0px)'; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment