Skip to content

Instantly share code, notes, and snippets.

@macu
Created December 8, 2016 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macu/bcd6422ad30544e14a97219148322312 to your computer and use it in GitHub Desktop.
Save macu/bcd6422ad30544e14a97219148322312 to your computer and use it in GitHub Desktop.
Saves toggle state in localStorage and restores on next page load. Note this does not allow some plugins to calculate positions and dimensions of elements in the hidden area.
<a data-toggle=".demo-layout .demo-target" href="#">[-]</a>
<div class="demo-layout">
<div class="demo-target">
<p>Content hidden or displayed</p>
</div>
</div>
// support [-] and [+] toggle
$('a[data-toggle]')
.on('click', function(e) {
e.preventDefault();
var targetSelector = $(this).attr('data-toggle');
var $target = $(targetSelector);
if ($target.length) {
$target.toggle();
$(this).trigger('after-toggle');
}
})
.on('after-toggle', function() {
var targetSelector = $(this).attr('data-toggle');
var $target = $(targetSelector);
$(this).text('[' + ($target.is(':visible') ? '-' : '+') + ']');
if ($target.length && window.localStorage && window.localStorage.setItem) {
// save toggle state
window.localStorage.setItem(targetSelector, $target.is(':visible') ? 'visible' : 'hidden');
}
})
.each(function() {
var targetSelector = $(this).attr('data-toggle');
var $target = $(targetSelector);
if ($target.length && window.localStorage && window.localStorage.getItem) {
// restore saved toggle state
switch (window.localStorage.getItem(targetSelector)) {
case 'visible':
$target.show();
break;
case 'hidden':
$target.hide();
break;
}
$(this).trigger('after-toggle');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment