Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // automatically rename the text on back button to show the panel name
- //e.g. 'back to reviews' instead of the default text 'back'
- const updateBackText = 1; // true (1) or false (0)
- // calculate header height for mobile menu top offset
- const calcHeaderHeight = 1; // true (1) or false (0)
- // mobile breakpoint
- const mq = window.matchMedia("(max-width: 1024px)");
- // automatically opens the current menu item's panel
- const autoCurrentPosition = 1; // true (1) or false (0)
- const enableTopBar = 1;
- const enableOffCanvas = 0;
- const offCanvasBreakpoint = window.matchMedia("(max-width:10024px)");
- const offCanvasPushContent = 0; // enable offcanvas for this to work
- const fixedNavTrigger = 0; // fix the toggle button when pushing content
- const openFirstDropDown = 0; // open first dropdwon conent on page load
- const autoCloseDropdown = 1; // automaticaly close dropdown when it loses focus
- const overlaySidebar = 0; // overlays the sidebar on a fullwidth page | disable offcanves for this to work
- const overlayTopBar = 0; // overlays the topbar when using offcanvas
- const enableRTL = 0; // support for RTL layout
- const offsetHashLinkScroll = 1; // add offset when scrolling to hashlink, useful for sticky header
- if (enableTopBar && !enableOffCanvas){
- document.body.classList.add('dwc-topbar-enabled')
- }
- if (enableRTL){
- document.body.classList.add('dwc-rtl')
- }
- if (overlaySidebar && !enableOffCanvas){
- document.body.classList.add('dwc-overlay-sidebar')
- }
- if (overlayTopBar && enableOffCanvas){
- document.body.classList.add('dwc-overlay-topbar')
- }
- //document.addEventListener('DOMContentLoaded', () => {
- const header = document.querySelector("header");
- const navTrigger = document.querySelector(".dwc-nav-trigger");
- const closeBtn = document.querySelector(".dwc-sidebar__nav-close-btn");
- const mobileMenuOverlay = document.querySelector(".dwc-mobile-menu-overlay");
- const body = document.body;
- const nav = document.querySelector('.dwc-sidebar__nav');
- const homePanel = document.querySelector('.dwc-sidebar__nav__panel--home');
- const dropdownToggles = document.querySelectorAll('.dwc-sidebar__dropdown-toggle [role = "button"]');
- const dropdownContents = document.querySelectorAll('.dwc-sidebar__dropdown-content');
- const menuLinks = document.querySelectorAll('.dwc-sidebar__nav__li a');
- const offCanvasMobileOnly = offCanvasBreakpoint.matches;
- const select = selector => document.querySelectorAll(selector);
- const initInert = () => select('.dwc-sidebar__nav__panel').forEach(nPanel => {
- mobileMenuIsClosed()
- if (!nPanel.classList.contains('dwc-sidebar__nav__panel--home')) {
- nPanel.inert = true;
- } else {
- nPanel.inert = false;
- }
- });
- //OPEN FIRST DROP DOWN
- if (openFirstDropDown){
- setTimeout(function () {
- dropdownToggles[0].click();
- }, 600);
- }
- // Get DROPWDOWN LEVELS
- dropdownContents.forEach(function (element) {
- let level = 1;
- let parent = element.parentElement.closest('.dwc-sidebar__dropdown-content');
- // Calculate the level by checking the number of ancestors
- while (parent) {
- level++;
- parent = parent.parentElement.closest('.dwc-sidebar__dropdown-content');
- }
- // Assign the appropriate level class to the dropdown content
- element.classList.add(`level-${level}`);
- // Find the previous sibling with the class .dwc-sidebar__dropdown-toggle
- const previousToggle = element.previousElementSibling;
- // Check if the previous sibling is a dropdown toggle and assign the level class
- if (previousToggle && previousToggle.classList.contains('dwc-sidebar__dropdown-toggle')) {
- previousToggle.classList.add(`level-${level}`);
- }
- });
- // CURRENT MENU ITEM ****************
- // Get the current page address without trailing slash
- var currentPage = window.location.pathname.replace(/\/$/, '');
- for (var i = 0; i < menuLinks.length; i++) {
- var link = menuLinks[i];
- // Extract the pathname from the link's href attribute without trailing slash
- var linkPathname = link.href.replace(window.location.origin, '').replace(/\/$/, '');
- // Check if the pathname matches the current page
- if (linkPathname === currentPage) {
- // Add the class 'dwc-current-menu-item' to the matching link
- link.classList.add("dwc-current-menu-item");
- // Break out of the loop since we found the matching link
- break;
- } else {
- // Skip to the next iteration if the link doesn't match
- continue;
- }
- }
- setTimeout(function () {
- const currentDropDownLink = document.querySelector('.dwc-current-menu-item.dwc-sidebar__nav__link');
- if (currentDropDownLink) {
- const parent = currentDropDownLink.closest('.dwc-sidebar__dropdown-content');
- if (parent) {
- const toggle = parent.previousElementSibling.querySelector('[role="button"]');
- if (toggle) {
- toggle.click();
- }
- }
- setTimeout(function () {
- currentDropDownLink.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
- //console.log(currentDropDownLink);
- }, 500);
- }
- }, 1800);
- // CURRENT MENU ENDS **********
- // CURRENT MENU CHECK - we'll be using this to determine if to reset panels on navTrigger click or not
- var hasCurrentMenu = Array.from(document.querySelectorAll(".dwc-sidebar__nav__link.dwc-current-menu-item")).some(function (link) {
- var parentPanel = link.closest(".dwc-sidebar__nav__panel");
- return !parentPanel || !parentPanel.classList.contains("dwc-sidebar__nav__panel--home");
- });
- // CURRENT CHECK ENDS *********************
- const goHome = () => select('.dwc-sidebar__nav__panel').forEach(nPanel => {
- nPanel.classList.remove('dwc-slide-left');
- if (!nPanel.classList.contains('dwc-sidebar__nav__panel--home')) {
- nPanel.classList.add('dwc-slide-right');
- nPanel.inert = true;
- } else {
- nPanel.inert = false;
- if (header && !mq.matches) {
- header.setAttribute('tabindex', 0);
- header.focus()
- }
- }
- select('.dwc-sidebar__nav__btn:not(.dwc-nav__back-btn)').forEach(sbtn => {
- sbtn.setAttribute('aria-expanded', 'false');
- })
- mobileMenuIsClosed()
- //window.addEventListener("resize", mobileMenuIsClosed);
- });
- window.addEventListener("resize", mobileMenuIsClosed);
- select('.dwc-nav__home-btn').forEach(hbtn => hbtn.addEventListener('click', goHome));
- nav.addEventListener('keydown', event => {
- if (nav.contains(event.target)) {
- if (event.key === 'Escape') {
- if (body.classList.contains('dwc-slide-nav-open')) {
- if (navTrigger) {
- navTrigger.click()
- navTrigger.focus()
- }
- goHome();
- } else {
- goHome();
- }
- }
- }
- });
- select('.dwc-sidebar__nav__btn:not(.dwc-nav__back-btn)').forEach(sbtn => {
- sbtn.setAttribute('aria-expanded', 'false');
- sbtn.addEventListener('click', function (e) {
- initCollapseContent();
- dropdownToggles.forEach((togglebtn) => {
- togglebtn.setAttribute('aria-expanded', 'false');
- });
- e.preventDefault();
- e.stopPropagation();
- const targetId = this.getAttribute('data-title');
- const targetElement = document.querySelector(`.dwc-sidebar__nav__panel[data-title="${targetId}"]`);
- const parentPanel = this.closest('.dwc-sidebar__nav__panel');
- targetElement.classList.remove('dwc-slide-right');
- targetElement.inert = false;
- targetElement.setAttribute('tabindex', 0);
- targetElement.focus();
- ariaExpanded = !targetElement.classList.contains('dwc-slide-right');
- sbtn.setAttribute('aria-expanded', ariaExpanded);
- select('.dwc-nav__back-btn').forEach(bbtn => {
- bbtn.addEventListener('click', function (e) {
- ariaExpanded = !targetElement.classList.contains('dwc-slide-right');
- sbtn.setAttribute('aria-expanded', ariaExpanded);
- })
- })
- if (!parentPanel.classList.contains('dwc-slide-right')) {
- parentPanel.classList.add('dwc-slide-left');
- parentPanel.inert = true;
- }
- //handle back button data-title and back to feature
- let bbtn = targetElement.querySelector('.dwc-nav__back-btn');
- bbtnTitle = parentPanel.getAttribute('data-title');
- if (bbtn) {
- bbtn.setAttribute('data-title', bbtnTitle);
- bbtn.setAttribute('aria-label', 'Go back to ' + bbtnTitle + ' menu');
- //console.log(bbtnTitle)
- if (updateBackText) {
- bbtn.querySelector('.dwc-nav__back__text').textContent = 'back to ' + bbtnTitle;
- }
- }
- });
- })
- select('.dwc-nav__back-btn').forEach(bbtn => {
- const btnTitle = bbtn.getAttribute('data-title');
- bbtn.addEventListener('click', function (e) {
- e.preventDefault();
- e.stopPropagation();
- const returnBtnAttr = this.getAttribute('data-title');
- select('[data-title].dwc-sidebar__nav__panel').forEach(returnTarget => {
- if (returnTarget.getAttribute('data-title') === returnBtnAttr) {
- returnTarget.classList.remove('dwc-slide-left');
- returnTarget.inert = false;
- if (returnTarget.classList.contains('dwc-sidebar__nav__panel--home')) {
- if (header) {
- header.setAttribute('tabindex', 0);
- header.focus()
- }
- } else {
- returnTarget.setAttribute('tabindex', 0);
- returnTarget.focus();
- }
- if (returnTarget.classList.contains('dwc-slide-right')) {
- returnTarget.classList.remove('dwc-slide-right');
- }
- }
- });
- const parentPanel = this.closest('.dwc-sidebar__nav__panel');
- parentPanel.classList.add('dwc-slide-right');
- parentPanel.inert = true;
- });
- });
- select('.dwc-sidebar__nav__panel').forEach(panel => {
- const panelTitle = panel.getAttribute('data-title');
- panel.setAttribute('aria-label', panelTitle + ' menu');
- });
- // mobile trigger
- function mobileMenuIsClosed() {
- if (mq.matches || enableOffCanvas) {
- const isNavOpen = body.classList.contains("dwc-slide-nav-open");
- navTrigger.setAttribute("aria-expanded", isNavOpen);
- if (isNavOpen) {
- if(!homePanel.classList.contains('dwc-slide-left')){
- homePanel.inert = false;
- }
- } else if (offCanvasMobileOnly){
- homePanel.inert = true;
- }
- } else {
- homePanel.inert = false;
- // console.log('desktop')
- }
- }
- function setNoScroll() {
- let noScrollTimeout;
- let clickCount = 1;
- let isNavOpen = body.classList.contains('dwc-slide-nav-open');
- // Check if 'dwc-slide-nav-open' class is applied
- if (isNavOpen) {
- body.classList.add('dwc-no-scroll');
- clickCount++;
- } else {
- clickCount = 0;
- }
- //console.log(clickCount)
- // Toggle 'dwc-no-scroll' class on the body if clickCount is odd
- if (clickCount == 0) {
- // Set a timer to remove 'dwc-no-scroll' class after 0.8 seconds
- noScrollTimeout = setTimeout(() => {
- isNavOpen = body.classList.contains('dwc-slide-nav-open');
- // console.log(isNavOpen)
- if(!isNavOpen){
- body.classList.remove('dwc-no-scroll');
- }
- }, 900);
- } else {
- // If 'dwc-no-scroll' class is removed by clicking again, clear the timeout
- clearTimeout(noScrollTimeout);
- }
- }
- if (navTrigger) {
- navTrigger.addEventListener("click", function () {
- body.classList.toggle("dwc-slide-nav-open");
- setNoScroll()
- mobileMenuIsClosed()
- if (!hasCurrentMenu && !autoCurrentPosition) {
- initCollapseContent()
- goHome();// watch out for this, could be problematic
- }
- dropdownToggles.forEach((togglebtn) => {
- //togglebtn.setAttribute('aria-expanded', 'false');
- });
- });
- }
- if (mobileMenuOverlay) {
- mobileMenuOverlay.addEventListener("click", function () {
- body.classList.remove("dwc-slide-nav-open");
- mobileMenuIsClosed()
- setNoScroll()
- if (!hasCurrentMenu && !autoCurrentPosition) {
- initCollapseContent()
- goHome()
- }
- });
- }
- if (closeBtn) {
- closeBtn.addEventListener("click", function () {
- body.classList.remove("dwc-slide-nav-open");
- mobileMenuIsClosed()
- setNoScroll()
- navTrigger.focus();
- if (!hasCurrentMenu && !autoCurrentPosition) {
- initCollapseContent()
- goHome()
- }
- });
- }
- //focus on mobile trigger when menu loses focus
- mobileMenuOverlay.addEventListener('focusin', (event) => {
- if (event.relatedTarget !== navTrigger && body.classList.contains("dwc-slide-nav-open")) {
- navTrigger.focus();
- }
- });
- const sidebarNavPanels = document.querySelectorAll(".dwc-sidebar__nav__panel");
- function updateSidebarPadding() {
- if (header && !enableOffCanvas) {
- // const headerHeight = header.clientHeight + 20;
- setTimeout(() => {
- const headerHeight = header.clientHeight + 20;
- // Your code to use headerHeight goes here
- sidebarNavPanels.forEach(function (sidebarNavPanel) {
- sidebarNavPanel.style.paddingTop = headerHeight + "px";
- });
- mobileMenuOverlay.style.marginTop = headerHeight - 20 + "px";
- }, 50);
- }
- }
- function resetPadding() {
- setTimeout(() => {
- sidebarNavPanels.forEach(function (sidebarNavPanel) {
- sidebarNavPanel.style.paddingTop = null;
- });
- }, 50);
- }
- function checkScreenSize() {
- if (mq.matches) {
- updateSidebarPadding();
- body.classList.add('dwc-mobile');
- } else {
- body.classList.remove('dwc-mobile');
- // if(!enableTopBar){
- resetPadding()
- // }
- }
- }
- if (calcHeaderHeight) {
- checkScreenSize();
- window.addEventListener("resize", checkScreenSize);
- }
- initInert()
- // ********* DROPDOWN TOGGLE FUNCNTIONALITY *******************
- function eCollapseContent(el, btn) {
- // Find the closest common ancestor, such as the <li> element
- const btnParentLi = btn.closest('li');
- dropdownContents.forEach((content) => {
- // Find the closest <li> ancestor for the dropdown content
- const contentParentLi = content.closest('li');
- // Check if the content and the button are at the same level
- const isSameLevel = btnParentLi && contentParentLi && btnParentLi.parentElement === contentParentLi.parentElement;
- // Check if the content is an ancestor of the dropdown toggle being clicked
- const isAncestor = btn && content.contains(btn);
- // Collapse the dropdown if it's not an ancestor of the toggle and is on the same level
- if (!isAncestor && isSameLevel) {
- content.style.maxHeight = '0';
- content.setAttribute('inert', 'true');
- // Update the aria-expanded attribute of the corresponding toggle button
- const correspondingToggle = content.previousElementSibling.querySelector('[role="button"]');
- if (correspondingToggle) {
- correspondingToggle.setAttribute('aria-expanded', 'false');
- }
- }
- });
- }
- function initCollapseContent(el, btn) {
- dropdownContents.forEach((content) => {
- content.style.maxHeight = '0';
- content.setAttribute('inert', 'true');
- });
- }
- function collapseContent(el, btn) {
- // Find the closest common ancestor, such as the <li> element
- const btnParentLi = btn.closest('li');
- dropdownContents.forEach((content) => {
- // Find the closest <li> ancestor for the dropdown content
- const contentParentLi = content.closest('li');
- // Check if the content and the button are at the same level
- const isSameLevel = btnParentLi && contentParentLi && btnParentLi.parentElement === contentParentLi.parentElement;
- // Check if the content is an ancestor of the dropdown toggle being clicked
- const isAncestor = btn && content.contains(btn);
- // Collapse the dropdown if it's not an ancestor of the toggle and is on the same level
- if (!isAncestor && isSameLevel) {
- content.style.maxHeight = '0';
- content.setAttribute('inert', 'true');
- }
- });
- }
- // Toggle the ARIA attributes for dropdown buttons
- function toggleAriaExpanded(activeToggle) {
- // If activeToggle is null, reset all buttons to 'false'
- if (activeToggle === null) {
- dropdownToggles.forEach((toggle) => {
- toggle.setAttribute('aria-expanded', 'false');
- });
- return; // Exit the function early since there's nothing else to do
- }
- dropdownToggles.forEach((toggle) => {
- if (toggle === activeToggle) {
- // Toggle the aria-expanded attribute for the clicked button
- const isOpen = toggle.getAttribute('aria-expanded') === 'true';
- toggle.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
- } else {
- // Check if the toggle's parent is a sibling to the activeToggle's parent
- const toggleParent = toggle.closest('li');
- const activeToggleParent = activeToggle.closest('li');
- // console.log('toggle parent', toggleParent)
- // console.log('active toggle parent', activeToggleParent)
- if (toggleParent && activeToggleParent && toggleParent.parentElement === activeToggleParent.parentElement) {
- // Set all other buttons' aria-expanded to false if their parent is a sibling to the activeToggle's parent
- toggle.setAttribute('aria-expanded', 'false');
- }
- }
- });
- }
- // Function to adjust the max-height of parent dropdowns when a nested dropdown is opened
- function adjustDropdownHeight(dropdownContent) {
- // Start with the nearest ancestor that is a dropdown content
- let parent = dropdownContent.closest('.dwc-sidebar__dropdown-content');
- while (parent) {
- // Calculate the cumulative height of all open children
- let totalHeight = Array.from(parent.children).reduce((total, child) => {
- // Add the child scrollHeight to the total if it's open
- total += child.scrollHeight;
- return total;
- }, 0);
- // Move to the next ancestor that is a dropdown content
- parent = parent.parentElement.closest('.dwc-sidebar__dropdown-content');
- if(parent){
- parentHeight = parent.scrollHeight;
- // Set the parent's max-height to the total calculated height
- parent.style.maxHeight = `${totalHeight + parentHeight}px`;
- // console.log('child: ', dropdownContent)
- // console.log('parent: ', parent)
- // console.log(`${totalHeight}px`)
- parent.inert = false;
- // console.log('parent new: ', parent)
- const parentParent = parent.closest('li')
- const toggle = parentParent.querySelector('.dwc-sidebar__dropdown-toggle [role = "button"]')
- toggle.setAttribute('aria-expanded', 'true');
- }
- }
- }
- // Initialize dropdowns
- function initializeDropdowns() {
- initCollapseContent();
- dropdownToggles.forEach((toggle, index) => {
- toggle.setAttribute('aria-expanded', 'false');
- const dropdownContent = dropdownContents[index];
- const parentDropdown = toggle.closest('.dwc-sidebar__dropdown');
- const dropdownLink = parentDropdown.querySelector('.dwc-nav__link__text');
- toggle.setAttribute('aria-label', `Toggle ${dropdownLink.textContent} dropdown`);
- toggle.addEventListener('click', function () {
- const isOpen = dropdownContent.style.maxHeight !== '0px';
- collapseContent(dropdownContent, this);
- if (!isOpen) {
- dropdownContent.inert = false;
- }
- toggleAriaExpanded(this);
- if (parentDropdown.contains(this)) {
- dropdownContent.style.maxHeight = isOpen ? '0' : `${dropdownContent.scrollHeight}px`;
- // Only adjust if opening the dropdown
- if (!isOpen) {
- adjustDropdownHeight(dropdownContent);
- // console.log('other child', dropdownContent)
- }
- }
- });
- toggle.addEventListener('keydown', (event) => {
- closeDropdownOnEscape(event, toggle);
- });
- });
- }
- // Close dropdowns on Escape key press
- function closeDropdownOnEscape(event, el) {
- if (event.key === 'Escape' && el.contains(event.target)) {
- event.stopPropagation();
- if (el.style.maxHeight !== '0px') {
- const button = el.previousElementSibling.querySelector('[role = "button"]');
- if (button) {
- el.style.maxHeight = '0';
- el.inert = true;
- button.focus();
- } else {
- initCollapseContent();
- el.focus();
- }
- toggleAriaExpanded(null); // Reset all buttons to 'false'
- }
- }
- }
- // Initialize dropdowns
- initializeDropdowns();
- dropdownContents.forEach((dropdownContent) => {
- // Add event listeners for closing dropdowns on Escape key press
- dropdownContent.addEventListener('keydown', (event) => {
- closeDropdownOnEscape(event, dropdownContent);
- });
- // close dropdown on focus lost
- if(autoCloseDropdown){
- const links = dropdownContent.querySelectorAll('a.dwc-sidebar__nav__link');
- links.forEach(link => {
- const linkParent = link.closest('.dwc-sidebar__dropdown-content');
- const dropDownButton = linkParent.previousElementSibling.querySelector('[role = "button"]')
- link.addEventListener('blur', () => {
- setTimeout(function () {
- if ([...links].every(link => !document.activeElement.isSameNode(link))) {
- eCollapseContent(dropdownContent, dropDownButton)
- }
- }, 50);
- });
- });
- }
- });
- // AUTOMATIC MENU POSITION
- function autoMenuPosition() {
- // Select the current menu item
- const currentMenuItem = document.querySelector('.dwc-current-menu-item');
- // Select the parent panel of the current menu item
- if (currentMenuItem) {
- const parentPanel = currentMenuItem.closest('.dwc-sidebar__nav__panel');
- const parentIsHome = parentPanel.classList.contains('dwc-sidebar__nav__panel--home')
- // Check if the parent panel has the 'dwc-sidebar__nav__panel--home' class
- if (!parentIsHome) {
- // Select the back button in the current menu's parent panel
- const backButton = parentPanel.querySelector('.dwc-nav__back-btn');
- // Remove the class 'dwc-slide-right' from the current menu's parent panel
- parentPanel.classList.remove('dwc-slide-right');
- // Get the data-title attribute of the current menu's parent panel
- // Loop through all panels with class .dwc-sidebar__nav__panel
- const allPanels = document.querySelectorAll('.dwc-sidebar__nav__panel');
- // Select all slide buttons .dwc-sidebar__nav__btn of each panel
- const slideButtons = document.querySelectorAll('.dwc-sidebar__nav__btn:not(.dwc-nav__back-btn)');
- slideButtons.forEach((slideButton) => {
- allPanels.forEach((panel) => {
- // Get the data-title attribute of the panel
- const eachPanelTitle = panel.getAttribute('data-title');
- // Get the back button in each of the panels
- const panelBackButton = panel.querySelector('.dwc-nav__back-btn');
- const slideTitle = slideButton.getAttribute('data-title')
- if (slideTitle === eachPanelTitle) {
- //get slide button parent
- const slideParentPanel = slideButton.closest('.dwc-sidebar__nav__panel');
- //get slide parent titlte attribute
- const slideParentTitle = slideParentPanel.getAttribute('data-title')
- // Set the back button title attribute to be equal to the title attribute of the slide parent panel
- panelBackButton.setAttribute('data-title', slideParentTitle);
- panelBackButton.querySelector('.dwc-nav__back__text').textContent = 'back to ' + slideParentTitle
- }
- });
- });
- homePanel.classList.add('dwc-slide-left');
- }
- if (!parentIsHome) {
- parentPanel.inert = false;
- homePanel.inert = true;
- }
- repositionReturnTargets()
- }
- }
- if (autoCurrentPosition) {
- setTimeout(function () {
- autoMenuPosition()
- }, 1000);
- }
- //function to reposition the hidden slides after automatically moving to current menu item panel
- // to put them in the right position to slide back to
- function repositionReturnTargets() {
- const panels = document.querySelectorAll('.dwc-sidebar__nav__panel:not(.dwc-sidebar__nav__panel--home)');
- let activePanel;
- // Find the first panel without 'dwc-slide-right' and 'dwc-slide-left' classes
- for (const panel of panels) {
- if (!panel.classList.contains('dwc-slide-right') && !panel.classList.contains('dwc-slide-left')) {
- activePanel = panel;
- break;
- }
- }
- let returnTarget;
- while (activePanel) {
- // Get the title attribute of each panel
- const panelTitles = Array.from(panels).map(panel => panel.getAttribute('data-title'));
- // Select the active back button in the active panel
- const activeBackButton = activePanel.querySelector('.dwc-nav__back-btn');
- // Find the returnTarget panel
- returnTarget = Array.from(panels).find(panel => panel.getAttribute('data-title') === activeBackButton.getAttribute('data-title'));
- // Remove and add classes to the returnTarget
- if (returnTarget) {
- returnTarget.classList.remove('dwc-slide-right');
- returnTarget.classList.add('dwc-slide-left');
- }
- // Update activePanel for the next iteration
- activePanel = returnTarget;
- }
- }
- // *********AUTOMATIC ENDS************
- // Button without button tag click on ENTER
- header.addEventListener('keydown', function (event) {
- if (event.key === 'Enter' && event.target.matches('[role="button"]')) {
- // Check if the target element is a button and if the Enter key was pressed
- event.target.click();
- }
- });
- // **************OFFCANVAS *****************
- if (offCanvasPushContent) {
- // Create a new div element with the class "site-wrapper"
- var siteWrapper = document.createElement('div');
- siteWrapper.className = 'dwc-site-wrapper';
- // Move everything within the body tag into the "site-wrapper" div
- while (document.body.firstChild) {
- siteWrapper.appendChild(document.body.firstChild);
- }
- // Add the "site-wrapper" div back to the body
- document.body.appendChild(siteWrapper);
- }
- function offCanvasInit() {
- if (enableOffCanvas && offCanvasBreakpoint.matches) {
- document.body.classList.add('dwc-offcanvas');
- if (offCanvasPushContent) {
- document.body.classList.add('dwc-push-content');
- if(fixedNavTrigger){
- document.body.classList.add('dwc-nav-trigger-is-fixed');
- }
- }
- // Function to check if header element is focusable
- function isFocusable(element) {
- const focusableTags = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'AREA'];
- return (
- focusableTags.includes(element.tagName) ||
- element.hasAttribute('tabindex') ||
- element.hasAttribute('contenteditable')
- );
- }
- // Function to set inert attribute for focusable elements
- function setInertForFocusableElements(inertValue) {
- const allElements = document.querySelectorAll('.dwc-header-inner-wrap *');
- const focusableElements = Array.from(allElements).filter(element => {
- return isFocusable(element) && !element.classList.contains('dwc-nav-trigger');
- });
- focusableElements.forEach(element => {
- if (element) {
- element.inert = inertValue;
- }
- });
- }
- // Click event listener for the 'nav-trigger'
- header.addEventListener('click', function () {
- const isNavOpen = document.body.classList.contains('dwc-slide-nav-open');
- // Check if the body contains the class 'dwc-slide-nav-open'
- if (isNavOpen) {
- // Condition is true, set inert=true
- setInertForFocusableElements(isNavOpen);
- } else {
- // Condition is false, set inert=false
- setInertForFocusableElements(isNavOpen);
- }
- });
- } else {
- document.body.classList.remove('dwc-push-content');
- document.body.classList.remove('dwc-offcanvas');
- }
- }
- offCanvasInit()
- window.addEventListener("resize", offCanvasInit);
- //close offcanvas when haslink is clicked
- if (enableOffCanvas) {
- const sidebarLinks = document.querySelectorAll('a.dwc-sidebar__nav__link');
- // Filter links with hash in the href attribute
- const hashLinks = Array.from(sidebarLinks).filter(link => link.getAttribute('href').includes('#'));
- // Add click event listener to each hash link
- hashLinks.forEach(link => {
- link.addEventListener('click', function(event) {
- // event.preventDefault(); // Prevent the default behavior of the link (e.g., navigating to the hash)
- // Perform a click action on the navTrigger button
- if (navTrigger) {
- navTrigger.click();
- }
- });
- });
- }
- //Document loaded end
- // });
- function debounce(func, delay) {
- let timeoutId;
- return function (...args) {
- clearTimeout(timeoutId);
- timeoutId = setTimeout(() => {
- func.apply(this, args);
- }, delay);
- };
- }
- // Your existing code for adding the 'hasHeaderHeight' class
- function addHeaderHeightClass() {
- if (!document.body) {
- // Body doesn't exist, keep checking
- setTimeout(addHeaderHeightClass, 0);
- return;
- }
- let hasHeaderHeight = document.body.classList.contains('hasHeaderHeight');
- let header = document.querySelector('header');
- if (!hasHeaderHeight && header) {
- // Header exists, add the 'hasHeaderHeight' class
- document.body.classList.add('hasHeaderHeight');
- // Get the initial header height
- updateHeaderHeight();
- } else if (!hasHeaderHeight && !header) {
- // Header doesn't exist, keep checking
- setTimeout(addHeaderHeightClass, 0);
- }
- }
- // Function to update header height and set the CSS variable
- function updateHeaderHeight() {
- let sidebar = document.querySelector('.dwc-header-inner-wrap');
- if (document.body) {
- let headerHeight = sidebar.offsetHeight;
- document.body.style.setProperty('--dwc-header-height', `${headerHeight}px`);
- }
- }
- // Add the 'hasHeaderHeight' class and set initial header height
- addHeaderHeightClass();
- // Attach the debounced update function to the window resize event
- const debouncedUpdateHeaderHeight = debounce(updateHeaderHeight, 50);
- window.addEventListener('resize', debouncedUpdateHeaderHeight);
- // Smooth scroll to hashlink with an offset
- function smoothScroll(target, offset) {
- const targetElement = document.querySelector(target);
- if (targetElement) {
- const targetPosition = targetElement.getBoundingClientRect().top -
- document.body.getBoundingClientRect().top -
- offset;
- window.scrollTo({
- top: targetPosition,
- behavior: 'smooth'
- });
- }
- }
- // Listen for hash link clicks
- if(offsetHashLinkScroll){
- document.querySelectorAll('a[href^="#"]').forEach(anchor => {
- anchor.addEventListener('click', function (e) {
- var headerElement = document.querySelector('.dwc-header-inner-wrap');
- var offset = headerElement.offsetHeight;
- e.preventDefault();
- event.stopPropagation();
- const href = this.getAttribute('href');
- smoothScroll(href, offset);
- });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment