Skip to content

Instantly share code, notes, and snippets.

@Ahrengot
Created January 23, 2012 09:52
Show Gist options
  • Save Ahrengot/1662150 to your computer and use it in GitHub Desktop.
Save Ahrengot/1662150 to your computer and use it in GitHub Desktop.
Simple jQuery toggle class
var toggle = function(selector, parentSelector, switchMode, onSelect) {
var $items,
$containers;
this.init = function() {
$items = $(selector);
$containers = $items.parents(parentSelector);
$items.each(function() {
$(this).data('container', $(this).parents(parentSelector));
});
$items.click(function(e) {
e.preventDefault();
if (switchMode) {
$containers.removeClass('current');
$(this).data('container').addClass('current');
}
else {
$(this).data('container').toggleClass('current');
}
if (onSelect) onSelect($(this));
});
};
return this;
}
@Ahrengot
Copy link
Author

Use this where normal toggle functionality isn't sufficient. For instance if you want <a> links inside a list to toggle their parent <ul> container instead of themselves. Example:

HTML:

<ul class="nav">
    <li><a href="#">link1</a></li>
    <li><a href="#">link2</a></li>
</ul>

<ul class="nav">
    <li><a href="#">link1</a></li>
    <li><a href="#">link2</a></li>
    <li><a href="#">link3</a></li>
</ul>

JavaScript:

var myToggler = new toggle('ul.nav a', 'ul.nav').init();

CSS:

ul.nav.current { background: red; }

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