Navbar JavaScript API

The Navbar component can be initialized on a <nav> element as well as an <ul> via JavaScript API, which is useful for dynamic content and complete control over the initialization, public method and/or options.

Navbar Initialization

When you don't use the specific DATA API attribute data-function="navbar", you can initialize very easy via JavaScript API.

// import into your project
import Navbar from '@thednp/navbar';

// initialize your target
const myNavbarInit = new Navbar('#myNavbar');

Alternatively you can initialize any <ul class="nav"> element:

// import into your project
import Navbar from '@thednp/navbar';

// alternativelly initialize on a UL target
// without the navbar wrapper
const myMenu = document.querySelector('ul.nav');
const myMenuInit = new Navbar(myMenu);

Set the right options for your navigation:

// import into your project
import Navbar from '@thednp/navbar';

// initialize with options
const myMenuInit = new Navbar(
  'selector', // any valid selector
  {
    breakpoint: 800, // your value must be the same with SCSS variable value
    toggleSiblings: true,
    delay: 600
  }
);

In many cases you will find the default option values to be quite fine.

Access Initialization Object

Similar to our bootstrap.native components, you can access the Navbar initialization object like this:

// access an initialization object
const myNavbarInit = Navbar.getInstance('#myNavbar');

Custom Events

Considering the above initialization, we can also attach Navbar custom events:

// find any [LI > A] item you want to attach events
const myMenuItem = document.getElementById('my-item');

// add show.navbar handler
myMenuItem.addEventListener('show.navbar', function(e){
  // do some dew with this menu item
  // e.target is myMenuItem
});

// add shown.navbar handler
myMenuItem.addEventListener('shown.navbar', function(e){
  // do some dew with this menu item
  // e.target is myMenuItem
});

// add hide.navbar handler
myMenuItem.addEventListener('hide.navbar', function(e){
  // do some dew with this menu item
  // e.target is myMenuItem
});

// add hidden.navbar handler
myMenuItem.addEventListener('hidden.navbar', function(e){
  // do some dew with this menu item
  // e.target is myMenuItem
});

If a menu item is in fact a .column-title element, the events won't fire.

Destroy The Initialization

Considering the above initialization, we can destroy the initialization object via the .dispose() public method.

// remove navbar functionality from target
myMenuInit.dispose();

When calling the .dispose() method, aside from removing the component's event handlers, all sub-menus are also be closed.

JavaScript API Example

This example showcases all features, options and events. You should open your browser console as well as the source of this very page.