This is just a snippet but I will have many different links on a page. Each link will have a different hidden element associated with it. I\'m trying to avoid writing 100 diff
You may use given below toggle function to toggle multiple elements by giving array of element id as input.
For example:
toggleElements(["elem1","elem2"],["elem3"]); OR toggleElements(arr1,arr2);
function showElements(showEls){
for(var i=0; i<showEls.length; i++){
if($("#"+showEls[i]).is(':hidden')) $("#"+showEls[i]).show();
}
}
function hideElements(hideEls){
for(var i=0; i<hideEls.length; i++){
if($("#"+hideEls[i]).is(':visible')) $("#"+hideEls[i]).hide();
}
}
function toggleElements(arr1,arr2){
if(true){
if($("#"+arr1[0]).is(":hidden")){
showElements(arr1);
hideElements(arr2);
}else{
showElements(arr2);
hideElements(arr1);
}
}
}
You would ideally need a way to link the links to the right div. You can do this using the data attributes like this.
HTML:
<a class="county" data-divId="stats1" href="#">one</a><br/>
<a class="county" data-divId="stats2" href="#">two</a>
<div id="stats1" class="countystats">stats one</div>
<div id="stats2" class="countystats">stats two</div>
JS:
$('.county').click(function() {
$('#' + $(this).data('divId')).slideToggle();
});
Example - http://jsfiddle.net/infernalbadger/6wDf9/
This should be quite easy to do if you are dynamically generating these links.
You could use:
$('.county').click(
function(){
var thisIs = $(this).index();
$('.countystats').eq(thisIs).slideToggle(300);
});
JS Fiddle demo.
Note that I removed the br
from the html to get the index()
accurately. If you need a
elements to be one-per-line, use:
a {
display: block;
}
References: