Skip to content

Instantly share code, notes, and snippets.

@SimonPadbury
Last active May 21, 2018 09:08
Show Gist options
  • Save SimonPadbury/697d73e896a5fd0f0f09 to your computer and use it in GitHub Desktop.
Save SimonPadbury/697d73e896a5fd0f0f09 to your computer and use it in GitHub Desktop.
toggle_anything.js
#your-thing-id.your-toggle-class {
/*
Any styling you like can go in here, for example...
*/
background: yellow;
}
<span data-toggle-id="your-thing-id" data-toggle-class="your-toggle-class">Toggle that thing</span>
<div id="your-thing-id" >Your toggleable thing.</div>
(function ($) {
"use strict";
$(document).ready(function () {
$('[data-toggle-id]').click(function () {
var toggleID = $(this).attr('data-toggle-id'),
toggleClass = $(this).attr('data-toggle-class');
$("#" + toggleID).toggleClass(toggleClass);
$(this).toggleClass('is-toggled');
});
});
}(jQuery));

#Toggle Anything

A versatile little jQuery script for using any way you like.

Here's how to use it:

  1. All you need to do is add an id="" to any element you wish to make toggleable in your HTML.

  2. Then on another element (e.g. a SPAN styled as a button)

  • add data-toggle-id="" pointing to the ID of your toggleable element
  • add data-toggle-class="" to set the class that you wish to be added/removed on the toggleable element
  1. Style your toggleable element's two states (without and with its toggled class).

  2. [Optional:] there is a class .is-toggled that is added/removed on the toggler (e.g. SPAN). You can style that too if necessary.

Use CSS3 animations for best results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment