Toggle - markhowellsmead/helpers GitHub Wiki

A toggler is a functionality which allows the user to “toggle” an element open and closed by interacting with another element, like a button.

Parameters

Interaction element (button)

  • data-toggle contains the CSS-style identifier for the target element.
  • data-toggleclass is a class name which will be toggled on the document root element (html).

Target element (NAV)

  • data-toggleclass contains a class name which will be toggled on/off the target element when the interaction element is clicked.

HTML

<a class="is-icon burger show-for-small-only" data-toggle=".nav.main" data-htmlclass="burger-open">Show navigation</a>

<nav class="mod nav main" data-toggleclass="open">
    <ul>
        <li><a href="/about/">About</a></li>
        <li><a href="/news/">News</a></li>
    </ul>
</nav>

SCSS

A simple example.

.mod.nav.main {
    display: none;
    &.open {
        display: block;
    }
}

JavaScript

(function($){
    $('[data-toggle]').on('click.toggle', function(){
        var $target = $($(this).data('toggle'));
        var $targetclass = $target.data('toggleclass');
        if($targetclass){
            $target.toggleClass($targetclass);
        }

        // An optional class name which will be toggled on the
        // document root element when the button is clicked.
        var $htmlclass = $(this).data('htmlclass');
        if($htmlclass){
            $('html').toggleClass($htmlclass);
        }
    });
})(jQuery);

Author

Mark Howells-Mead | www.permanenttourist.ch | Since 5th November 2016

⚠️ **GitHub.com Fallback** ⚠️