Last active
August 29, 2015 14:25
-
-
Save stevetrask/cd3a2c24101dc80277dd to your computer and use it in GitHub Desktop.
show and hide other elements
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
<a href="#" data-collapse-target="search-bar" data-collapse-expand-text="expand">collapse</a> |
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(){ | |
$('[data-collapse-target]').each(function(){ | |
/** | |
* Apply these data attributes to the a|button element to show|hide other elements | |
* | |
* data-collapse-target (ID of the element to show/hide) | |
* data-collapse-initial-state ("visible" or "hidden", defines the current visibilty of the target element) | |
* data-collapse-expand-text (button text to show when the target element is hidden) | |
* data-collapse-collapse-text (button text to show when the target element is visible) | |
*/ | |
var button = $(this); | |
var targetSelector = '#' + button.attr('data-collapse-target'); | |
var target = $(targetSelector); | |
var visible = true; | |
var initialState = button.attr('data-collapse-initial-state'); | |
if(initialState && initialState === 'hidden'){ | |
visible = false; | |
} | |
else if(!initialState){ | |
visible = target.is(':visible'); | |
} | |
var collapseText = button.attr('data-collapse-collapse-text'); | |
if(!collapseText) collapseText = button.text(); | |
var expandText = button.attr('data-collapse-expand-text'); | |
if(!expandText) expandText = button.text(); | |
button.click(function(e){ | |
e.preventDefault(); | |
if(visible){ | |
button.text(expandText); | |
target.slideUp(); | |
} | |
else{ | |
button.text(collapseText); | |
target.slideDown(); | |
} | |
// Visible > Hidden, Hidden > Visible | |
visible = !visible; | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment