Organizational Research By

Surprising Reserch Topic

Question:how to toggle element using java-script?



asked Sep 13, 2013 in JAVASCRIPT by rajesh
edited Sep 12, 2013
0 votes
22 views



Related Hot Questions

1 Answer

0 votes

 

TOGGLING THE SHORT WAY
// showing
 
document.getElementById('element').style.display = '';
 
// hiding
 
document.getElementById('element').style.display = 'none';
So let's make this into a function that'll get the job done real quick like:
SHOW? OR HIDE?
function toggle(obj) {
 
var el = document.getElementById(obj);
 
if ( el.style.display != 'none' ) {
 
el.style.display = 'none';
 
}
 
else {
 
el.style.display = '';
 
}
 
}
Well that was easy. But we can also go ternary style.
TOGGLING TERNARY STYLE
function toggle(obj) {
 
var el = document.getElementById(obj);
 
el.style.display = (el.style.display != 'none' ? 'none' : '' );
 
}
Cool. Hey, ever heard of the dollar function? If that's sittin' around somewhere, let's use it!
TOGGLING WITH THE TERNARY DOLLAR
// our dollar function
 
function $() {
 
var elements = new Array();
 
for (var i = 0; i < arguments.length; i++) {
 
var element = arguments[i];
 
if (typeof element == 'string')
 
element = document.getElementById(element);
 
if (arguments.length == 1)
 
return element;
 
elements.push(element);
 
}
 
return elements;
 
}
 
// and now our improved toggler!
 
function toggle(obj) {
 
var el = $(obj);
 
el.style.display = (el.style.display != 'none' ? 'none' : '' );
 
}
Cool. Now that we've got this thing nice and compact... can't we do anything else to make it cool? Why, of course. Let's say, instead of limitting it to just one object, let's say "unlimitted."
TOGGLING MULTIPLE OBJECTS
function toggle() {
 
for ( var i=0; i < arguments.length; i++ ) {
 
$(arguments[i]).style.display = ($(arguments[i]).style.display != 'none' ? 'none' : '' );
 
}
 
}
Sweet. Now that looks nice and sexy (quite personally, I think it's the sexi'est'). But let's see if we can extract any of these into "showing" versus "hiding" using an object literal.
answered Sep 13, 2013 by rajesh
edited Sep 12, 2013

...