Skip to content

Instantly share code, notes, and snippets.

@mishalrai
Last active March 12, 2020 03:19
Show Gist options
  • Save mishalrai/c44cf35902845b8b44ff36a55fbdd2ed to your computer and use it in GitHub Desktop.
Save mishalrai/c44cf35902845b8b44ff36a55fbdd2ed to your computer and use it in GitHub Desktop.
/**
* Show the Navigation around the screen
*/
+(function($){
class ShowNavOnScreen{
/**
* Initialize the necessory functions on initial load
*/
constructor(config){
if(!config.selector){
console.log('Must pass the selector on config');
return;
};
this.rightPositionCSS = { 'left': 'initial', 'right': '100%' }
this.selector = config.selector;
this.handleHoverEvent();
this.windowSize = $(window).width();
}
/**
* This function update windowSize value
* on window resize event
* @returns {void}
*/
updateWindowSize(){
$(window).on('resize', ()=>{
this.windowSize = $(window).width()
})
};
/**
* This function change the position of
* sub menu to the right
* @returns {void}
*/
changePosition($ele){
$ele.css(this.rightPositionCSS)
};
/**
* This function calculate the submenu size and
* change the position to visible on screen
* @uses ['changePosition']
* @param {object} e - event
* @returns {void}
*/
calSubMenuWidth(e){
/* Here target element should be a tag */
const $subMenu = $('+ul', $(e.target));
/* If we don't have sub menu then return from here */
if(!$subMenu.length) return;
const submenuWidth = $subMenu.outerWidth(true);
const submenuLeftOffset = $subMenu.offset().left;
const totalSizeOfSubMenu = submenuLeftOffset + submenuWidth;
/* If submenu goes to out of window then change the position */
(totalSizeOfSubMenu > this.windowSize) && this.changePosition($subMenu)
};
/**
* Listion hover event on selector and call the
* calSubMenuWidth functon
* @uses ['calSubMenuWidth']
* @returns {void}
*/
handleHoverEvent(){
$(this.selector).on('hover', e=>{
this.calSubMenuWidth(e)
});
}
}
$(document).ready(()=>{
/**
* Configuratin object
* Selector should be second level ul which is positioning absolute
*/
const config = {
selector: '#site-navigation ul ul li'
};
new ShowNavOnScreen(config);
})
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment