Created
January 23, 2012 09:52
-
-
Save Ahrengot/1662150 to your computer and use it in GitHub Desktop.
Simple jQuery toggle class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
JavaScript:
CSS: