Skip to content

Instantly share code, notes, and snippets.

@nadavspi
Created February 25, 2015 22:53
Show Gist options
  • Select an option

  • Save nadavspi/e2096b83437a0fa85fba to your computer and use it in GitHub Desktop.

Select an option

Save nadavspi/e2096b83437a0fa85fba to your computer and use it in GitHub Desktop.
togglesingle-improved.js
jQuery.fn.toggleSingle = function (options) {
// passing destruct: true allows
var settings = $j.extend({
destruct: false
}, options);
return this.each(function () {
if (!settings.destruct) {
var $this = $j(this);
var $next = $this.next();
// Give the content an ID if it doesn't have one
// For aria-controls
if (!$next.attr('id')) {
$next.attr('id', 'toggle-' + Math.random().toString(36).substr(2, 9));
}
// initialize ARIA attributes
$this.attr('aria-controls', $next.attr('id'));
$next.attr('aria-expanded', 'false');
$this.on('click', function () {
$this.toggleClass('active')
.attr('aria-expanded', !$this.attr('aria-expanded') === 'true');
$next().toggleClass('no-display')
.attr('aria-hidden', !$next.attr('aria-hidden') === 'true')
.focus();
});
// Hide the content
$this.next().addClass('no-display');
} else {
// Remove event handler so that the toggle link can no longer be used
$this.off('click');
// Remove all classes that were added by this plugin
$this.removeClass('active');
$next.removeClass('no-display');
// Remove ARIA attributes
$this.attr('aria-controls', null).attr('aria-expanded', null);
$next.attr('aria-hidden', null);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment