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 );