Last active
August 29, 2015 13:56
-
-
Save Azeirah/9315595 to your computer and use it in GitHub Desktop.
jQuery toggler plugin.
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
(function ($) { | |
$.fn.toggler = function () { | |
var prefix = "data-az", | |
toggle_groups = $(document).find("[" + prefix + "-toggle-group]"), | |
togglable_groups = $(document).find("[" + prefix + "-togglable-group]"), | |
togglables = togglable_groups.find("[" + prefix + "-togglable]"), | |
toggles = toggle_groups.find("[" + prefix + "-toggle]"); | |
togglables.hide(); | |
toggles.click(function () { | |
var data = $(this).data("az-toggle"), | |
toggle_group, | |
group_data, | |
togglable_group; | |
if (toggle_groups.length === 1) { | |
toggle_group = toggle_groups; | |
} else { | |
toggle_group = toggle_groups.has("[" + prefix + "-toggle='" + data + "']"); | |
} | |
if (togglable_groups.length === 1) { | |
togglable_group = togglable_groups; | |
} else { | |
togglable_group = togglable_groups.has("[data-togglable-group='" + group_data + "']"); | |
} | |
group_data = toggle_group.data("az-toggle-group"); | |
// hide everything else in the same group. | |
togglable_group.find("[" + prefix + "-togglable]").hide(); | |
togglable_group.find("[" + prefix + "-togglable='" + data + "']").show(); | |
}); | |
}; | |
}(jQuery)); |
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
I made toggler to quicky toggle on and off certain parts of the websites whenever an element is pressed. | |
The toggler function requires 4 things in your html code. | |
data-az-toggle-group | |
data-az-toggle | |
data-az-togglable-group | |
data-az-togglable | |
-az- is a prefix, I wanted to use this in combination with bootstrap, bootstrap uses data-toggle for buttons, so I added a prefix to prevent overriding bootstrap options. | |
data-az-toggle and data-az-togglable are linked. It's the same for the groups. | |
Whenever you click a button with `data-az-toggle="secret_content"`, all elements with `data-az-togglable="secret_content"` will be shown. | |
Everything else in the same group will be hidden. | |
You only need to call `$(document).toggler()` once. If your toggle buttons or your togglable content is dynamic, you need to call `$(document).toggler()` again whenever a new button or new content was added. | |
Example codepen: http://codepen.io/Azeirah/pen/IuEnk |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment