Skip to content

Instantly share code, notes, and snippets.

@davidsword
Last active March 5, 2019 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsword/12ca4e09dff1658beec7e5728cbc10d0 to your computer and use it in GitHub Desktop.
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
// 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