Dumb jQuery menu state plugin

in code

It’s dumb in the savant sense – there’s nothing more complex than a class toggle to hide other menu items when a button is clicked. The state manager links a button a button or hyperlink with a target element. When the button is clicked, classes are added to both the button and the target element. In this way I can control the open and closing of of several menu states with little effort.

I use it for the search on this site, if you care to play around with it live.

$.fn.link = function(args) {
    var defaults = {
        child: '',
        childClass: '',
        target: '',
        targetClass: '',
        linkedClass: '.linked-class-toggle',
        isTargetInput: false,
        toggled: false

    var opts = {};

    function clickToggle(event, override) {
        if (typeof override !== 'boolean' && !opts.toggled) {
            // Hide all other linked elements.
            $(opts.linkedClass).not(this).trigger('click', false);

        // opts.toggled can be overriden. Otherwise, just invert it.
        opts.toggled = (typeof override === 'boolean') ? override : !opts.toggled;

        $(opts.child).toggleClass(opts.childClass, opts.toggled);
        $(opts.target).toggleClass(opts.targetClass, opts.toggled);

        if (opts.toggled && opts.isTargetInput) {

    function closeOnEscape(event) {
        // Will /probably/ only work if target has tabindex set.
        if (event.keyCode === 27) {
            $(opts.button).trigger('click', false);

    opts = $.extend({}, defaults, args);
    opts.button = this;

    /* There is a class for all linked elements. On button click all are
     * hidden. */

        .on('click', clickToggle)
        .trigger('click', opts.toggled)

    // Trigger false on escape keyup and window resize.

    $(window).on('keyup', closeOnEscape);

    $(window).on('resize', function() {
        $(opts.button).trigger('click', false);

    return this;

Calling it requires the button selector, child selector, child toggle class, target, target toggle class, and whether or not the target is an input. There is a separate child class selector because of how I style buttons on the site.

    child: '.toggle-icon',
    childClass: 'close',
    target: '#bigsearch',
    targetClass: 'show',
    isTargetInput: true


in me

Your email address will not be published. Required fields are marked *