1. Docs
  2. Navbar toggler

Navbar toggle

A usefull function to create easily an interactive navbar

The toggleNavbar function creates a toggle mechanism specifically for navigational elements, with optional overlay functionality.

Purpose

  • To toggle the visibility of a navigation menu
  • To control body scroll when the navigation is open (optional)
  • To manage an optional overlay element

Usage

import { toggleNavbar } from '@flexilla/utilities';

toggleNavbar({
  navbarElement: '#mainNavbar',
  allowBodyScroll: false
});

Parameters

The toggleNavbar function accepts an options object with the following properties:
  • navbarElement: A string selector or HTMLElement representing the navbar to be toggled
  • allowBodyScroll: (Optional) A boolean indicating whether to allow body scrolling when the navbar is open (default: false)
  • onToggle: (Optional) A callback function that receives the current toggle state

HTML Structure

For the toggleNavbar function to work correctly, your HTML should have the following structure:
<button data-nav-trigger data-toggle-nav="mainNavbar">Toggle Menu</button>

<nav id="mainNavbar">
  <!-- Navigation content -->
</nav>

<div data-nav-overlay data-navbar-id="mainNavbar" aria-hidden="true" class="navbar-overlay-class"></div>

Behavior

  • It sets up a click event listener on a trigger element (identified by data-nav-trigger and data-toggle-nav attributes)
  • When clicked, it toggles the data-state attribute of the navbar between “open” and “close”
  • It updates the data-expanded attribute of the trigger element
  • If allowBoyScroll is false, it toggles the overflow-y style of the body
  • If an overlay element exists (identified by data-navbar-id), it manages its visibility
  • It sets up click events to close the navbar when clicking on the navbar itself or the overlay (if not static)
  • It calls the onToggle callback (if provided) with the current toggle state

Example