Skip to content

Instantly share code, notes, and snippets.

@tammyhart
Created January 12, 2016 16:56
Show Gist options
  • Select an option

  • Save tammyhart/890f7470e3be4b0cb956 to your computer and use it in GitHub Desktop.

Select an option

Save tammyhart/890f7470e3be4b0cb956 to your computer and use it in GitHub Desktop.

Revisions

  1. Tammy Hart created this gist Jan 12, 2016.
    42 changes: 42 additions & 0 deletions toggle.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@

    var $toggle = $( '[data-toggle]' );

    function toggleOpen(event) {

    var $this = $( this ),
    object = $this.data( 'toggle' ),
    $object = $( '.' + object ), // the object we're toggling
    rel = $this.attr( 'rel' ), // the name of any related toggles
    $other = $toggle.filter( '[rel=' + rel + ']' ).not( $this ), // find another toggle with the same rel
    $otherObject = $( '.' + $other.data( 'toggle' ) ), // get the other toggle's object
    $all = $toggle.filter( '[data-toggle=' + object + ']' ); // get all the toggles that toggle this object

    if ( $this.attr( 'data-toggled' ) === 'on' ) {
    // close
    $object.removeClass( 'open' );
    $object.addClass( 'closed' );

    // turn related toggles off
    $all.attr( 'data-toggled', 'off' );

    // remove body class
    $body.removeClass( 'open-' + object );
    } else {
    // if there's corresponding buttons
    $other.attr( 'data-toggled', 'off' );
    $otherObject.addClass( 'closed' );
    $otherObject.removeClass( 'open' );

    // open
    $object.addClass( 'open' );
    $object.removeClass( 'closed' );

    // turn related toggles on
    $all.attr( 'data-toggled', 'on' );

    // add a body class
    $body.addClass( 'open-' + object );
    }
    }

    $toggle.on( 'click', toggleOpen );