Skip to content

Instantly share code, notes, and snippets.

@labmorales
Created June 7, 2019 15:19
Show Gist options
  • Save labmorales/bc660befd274d83d893e6aa126fab680 to your computer and use it in GitHub Desktop.
Save labmorales/bc660befd274d83d893e6aa126fab680 to your computer and use it in GitHub Desktop.
Drupal 8 - Menu Positioning Script
(function ($) {
var userLoggedIn = $('body.user-logged-in').length ? true:false;
// Only Runs if logged In
if(userLoggedIn){
$(window).resize(positionMenuIfLoggedPosition);
window.onload = function(){
positionMenuIfLoggedPosition();
};
initMenuPositionObserverMutator();
}
// Listens for menu class changes
function initMenuPositionObserverMutator(){
if(!$('body.user-logged-in').length || !window.MutationObserver) {
return;
}
// Select the node that will be observed for mutations
var targetNode = document.getElementById('toolbar-item-administration-tray');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: false, subtree: false };
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
mutationsList.forEach(function(mutation){
if (mutation.type == 'attributes' && mutation.attributeName === 'class') {
positionMenuIfLoggedPosition();
}
});
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
}
// Positions the menu, and corrects the body margin in my case '#main-navigation'
function positionMenuIfLoggedPosition() {
var menu = jQuery("#toolbar-bar");
var subMenu = $("#toolbar-item-administration-tray");
if(menu.length) {
var top = menu.height();
var menuVertical = subMenu.hasClass("toolbar-tray-vertical");
var menuVerticalIsVisible = subMenu.is(":visible");
// Só usa a altura no posicionamento se o menu estiver na horizontal
var height = menuVertical ? 0 : subMenu.height();
var topOffset = top;
if(menuVerticalIsVisible) {
topOffset += height;
}
// Change for your menu selector HERE
$("#main-navigation").css({"top": topOffset+"px"});
$("body").css({"padding-top": topOffset});
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment