First, there's a function that will create a unique toggle function for whatever element you give it. Then, we wait for the window to load, and when it does, we create some toggle functions. In this example, we assume you have an element with id='some_id', but you can use whatever you need to get an element. Then, we stick the toggle function into a global variable.
// returns a function that will toggle the given element
function makeToggleFunction(el) {
var element = el;
return function() {
if (element.style.display == 'none')
element.style.display = 'block';
else
element.style.display = 'none';
};
}
window.addEventListener('load', on_window_load, false);
var GLOBAL = {};
function on_window_load() {
GLOBAL.toggle_element = makeToggleFunction(document.getElementById('some_id'));
}
You can then toggle the element whenever you need, with GLOBAL.toggle_element()
.
Also, I think this is the code for IE if you want to wait for the page to load.
document.addEventListener("DOMContentLoaded", on_window_load, false);
EDIT:
Add this function (from http://www.dustindiaz.com/getelementsbyclass/ as mentioed by programatique)
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
And then add the following inside the function on_window_load
:
GLOBAL.toggleable = new Array();
or each(var element in getElementsByClass('toggle')) {
GLOBAL.toggleable.push(makeToggleFunction(element));
}
GLOBAL.toggle_all = function() {
for each(var f in GLOBAL.toggleable) {
f.call();
}
};
And now you can call GLOBAL.toggle_all()
and it will hide all elements that have the class toggle
.