HC Off-canvas Nav

repository·master·Indexed 43 days ago

https://github.com/somewebmedia/hc-offcanvas-nav

A dependency-free JavaScript library (v6.2.5) for creating accessible, multi-level off-canvas navigation menus. It supports touch gestures, ARIA design patterns for dialogs, and provides both Vanilla JS and jQuery initialization. Features include a Carbon theme, customizable positioning, and a public API for controlling navigation state via methods like .open(), .close(), and .update().

Tokens
7.6K
Snippets
21
Records
22
Agent score
56%

What's inside HC Off-canvas Nav

  1. Access the HC Off-canvas Nav instance

    master

    To call methods on an existing instance, you must first capture the instance. In Vanilla JS, this is the object returned by the constructor. In jQuery, you can retrieve it using .data('hcOffcanvasNav').

    <!-- Vanilla JS -->
    var Nav = new hcOffcanvasNav();
    
    <!-- jQuery -->
    var $nav = $( '#main-nav' ).hcOffcanvasNav();
    var Nav = $nav.data( 'hcOffcanvasNav' );
  2. Integrate HC Off-canvas Nav with WordPress

    master

    To make WordPress menu outputs compatible with HC Off-canvas Nav (adding data-nav-active and data-nav-highlight attributes), add the following code to your theme's functions.php file.

    Note: Do not manually assign this custom Walker to your wp_nav_menu arguments; the filter handles the integration automatically and is compatible with existing custom Walkers.

    /*
     * Adds menu data support for HC Off-canvas Nav
     */
    
    $hc_nav_menu_walker;
    
    class HC_Walker_Nav_Menu extends Walker_Nav_Menu {
    
      public function start_lvl( &$output, $depth = 0, $args = array() ) {
        global $hc_nav_menu_walker;
        $hc_nav_menu_walker->start_lvl( $output, $depth, $args );
      }
    
      public function end_lvl( &$output, $depth = 0, $args = array() ) {
        global $hc_nav_menu_walker;
        $hc_nav_menu_walker->end_lvl( $output, $depth, $args );
      }
    
      public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        global $hc_nav_menu_walker;
    
        $item_output = '';
    
        $hc_nav_menu_walker->start_el( $item_output, $item, $depth, $args, $id );
    
        if ( $item->current_item_parent ) {
          $item_output = preg_replace( '/<li/', '<li data-nav-active', $item_output, 1 );
        }
    
        if ( $item->current ) {
          $item_output = preg_replace( '/<li/', '<li data-nav-highlight', $item_output, 1 );
        }
    
        $output .= $item_output;
      }
    
      public function end_el( &$output, $item, $depth = 0, $args = array() ) {
        global $hc_nav_menu_walker;
        $hc_nav_menu_walker->end_el( $output, $item, $depth, $args );
      }
    }
    
    add_filter( 'wp_nav_menu_args', function( $args ) {
      global $hc_nav_menu_walker;
    
      if ( ! empty( $args['walker'] ) ) {
        $hc_nav_menu_walker = $args['walker'];
      }
      else {
        $hc_nav_menu_walker = new Walker_Nav_Menu();
      }
    
      $args['walker'] = new HC_Walker_Nav_Menu();
    
      return $args;
    } );
  3. Use the Carbon theme

    master

    HC Off-canvas Nav includes two themes: default and Carbon. To use the Carbon theme, load the specific CSS file or include the corresponding SCSS files.

    <!-- CSS -->
    <link rel="stylesheet" href="/path/to/hc-offcanvas-nav.carbon.css">
    
    <!-- SCSS -->
    @use 'hc-offcanvas-nav/src/scss/core';
    @use 'hc-offcanvas-nav/src/scss/toggle';
    @use 'hc-offcanvas-nav/src/scss/theme-carbon' as theme-carbon;
    
    @include theme-carbon.styles();
  4. Use Data Attributes for Navigation Behavior

    master

    You can control the behavior and appearance of the navigation menu using HTML data-* attributes on <ul>, <li>, or <a> elements.

    <nav id="main-nav">
      <ul>
        <!-- Custom content cloning -->
        <li data-nav-custom-content>
          <div>Some custom content</div>
        </li>
        
        <!-- Highlighted item -->
        <li data-nav-highlight><a href="#">Home</a></li>
        
        <!-- Automatically open this sub-menu on next nav open -->
        <li data-nav-active>
          <a href="#">About</a>
          <ul data-nav-active>
            <li><a href="#">Team</a></li>
          </ul>
        </li>
        
        <!-- Prevent nav from closing when this link is clicked -->
        <li data-nav-close="false"><a href="#">Add Page</a></li>
      </ul>
    </nav>
  5. Include HC Off-canvas Nav in your project

    master

    Depending on your build system, you can include the library using standard script/CSS tags, module bundlers (Webpack/Browserify), Babel, or SCSS.

    <!-- Script and Css tag -->
    <link rel="stylesheet" href="/path/to/hc-offcanvas-nav.css">
    <script src="/path/to/hc-offcanvas-nav.js"></script>
    
    <!-- Webpack/Browserify -->
    const hcOffcanvasNav = require( 'hc-offcanvas-nav' );
    
    <!-- Babel -->
    import hcOffcanvasNav from 'hc-offcanvas-nav';
    
    <!-- SCSS -->
    @use 'hc-offcanvas-nav/src/scss/core';
    @use 'hc-offcanvas-nav/src/scss/toggle';
    @use 'hc-offcanvas-nav/src/scss/theme-default' as theme-default;
    
    @include theme-default.styles();
  6. Initialize HC Off-canvas Nav (Vanilla JS and jQuery)

    master

    To use the library, initialize it once your menu element is available in the DOM. You can use the Vanilla JS constructor or the jQuery plugin syntax.

    <!-- Vanilla JS -->
    document.addEventListener( 'DOMContentLoaded', function () {
      var Nav = new hcOffcanvasNav( '#main-nav', {
        disableAt: 1024,
        customToggle: '.toggle',
        navTitle: 'All Categories',
        levelTitles: true,
        levelTitleAsBack: true,
      } );
    } );
    
    <!-- jQuery -->
    jQuery( document ).ready( function ( $ ) {
      $( '#main-nav' ).hcOffcanvasNav( {
        disableAt: 1024,
        customToggle: $( '.toggle' ),
        navTitle: 'All Categories',
        levelTitles: true,
        levelTitleAsBack: true,
      } );
    } );
  7. Build the project using Gulp

    master

    The package uses Gulp for development tasks. You can run these via npx gulp.

    • npx gulp: Compiles JS and SCSS into /dist and builds demos into /docs.
    • npx gulp demo: Runs the default task and opens the demo HTML page.
    • npx gulp watch: Watches source JS and SCSS files and rebuilds automatically on save.

    Use the --dev flag to prevent minification of the compiled JS and CSS.

    npx gulp
    npx gulp watch
    npx gulp --dev
  8. Initialize HC Off-canvas Nav

    master

    To create an off-canvas navigation, instantiate the HcOffcanvasNav constructor. You can pass either a DOM element or a CSS selector string as the first argument. If a string is passed, the library will attempt to find the element using document.querySelector (if it starts with #) or document.querySelectorAll (otherwise).

    // Using a CSS selector
    const nav = new HcOffcanvasNav('#my-nav-element', { /* options */ });
    
    // Using a DOM element
    const element = document.querySelector('.my-nav');
    const nav = new HcOffcanvasNav(element, { /* options */ });
  9. Use HC Off-canvas Nav methods

    master

    The API provides several methods to control the navigation state, settings, and event listeners.

    <!-- .getSettings() -->
    var currentSettings = Nav.getSettings();
    
    <!-- .isOpen() -->
    if ( Nav.isOpen() ) {
      // do something
    }
    
    <!-- .update(options, updateDOM) -->
    // Update specific settings
    Nav.update( {
      disableAt: 1024,
      navTitle: 'All pages',
    } );
    
    // Update nav DOM only
    Nav.update( true );
    
    // Update both settings and nav DOM
    Nav.update(
      {
        disableAt: 1024,
        navTitle: 'All pages',
      },
      true
    );
    
    <!-- .open( level, index ) -->
    Nav.open(); // Opens the nav
    Nav.open( 2, 1 ); // Opens a specific sub menu at level 2, index 1
    
    <!-- .close() -->
    Nav.close();
    
    <!-- .toggle() -->
    Nav.toggle();
    
    <!-- .on( eventName, cb ) -->
    Nav.on( 'close', function () {
      // do something on close
    } );
    
    <!-- .off( eventName, cb ) -->
    Nav.off( 'close', onCloseFunction);
    Nav.off( 'close' );
  10. Listen to HC Off-canvas Nav events

    master

    The plugin emits several events that you can listen to using the .on() method. All event handlers receive two arguments: an Event object as the first argument and the plugin Settings object as the second.

    Event Timing

    • open, close, open.level, and close.level: Triggered after the navigation animation has completed.
    • toggle: Triggered immediately when the navigation is triggered to open or close.

    Event Data

    • open.level and close.level: The Event.data property contains the newly opened/closed currentLevel and currentIndex.
    • toggle: The Event.data property contains the action (e.g., 'open').
    // Example: Change nav position after each close
    Nav.on( 'close', function ( e, settings ) {
      Nav.update( {
        position: settings.position === 'left' ? 'right' : 'left',
      } );
    } );
    
    // Example: Access level data on level change
    Nav.on( 'open.level', ( e, settings ) => {
      console.log(e.data.currentLevel, e.data.currentIndex);
    } );
    
    // Example: Handle toggle action immediately
    Nav.on( 'toggle', ( e, settings ) => {
      if ( e.data.action == 'open' ) {
        // logic for when open is triggered
      }
    } );