Toggle an element with JavaScript

switch-off-512
View Details

There are litterally an unlimitted number of ways to toggle an element’s display with JavaScript. Some, more useful than others. Here is some of them , we will be happy if you add more functions !

 

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 = 'block'; // block can be replaced with inline , inline-block and so on .

	}

}

 

toggling ternary style

function toggle(obj) {

	var el = document.getElementById(obj);

	el.style.display = (el.style.display != 'none' ? 'none' : '' );
}

 

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' : '' );

	}

}

 

separating showing and hiding

var toggle = {

	show : function(obj) {

		document.getElementById(obj).style.display = '';

	},

	hide : function(obj) {

		document.getElementById(obj).style.display = 'none';

	}

};

 

separating showing and hiding

var toggle = {

	show : function(obj) {

		$(obj).style.display = '';

	},

	hide : function(obj) {

		$(obj).style.display = 'none';

	}

};

 

separating showing and hiding

var toggle = {

	show : function() {

		for ( i=0; i < arguments.length; i++ ) {

			$(arguments[i]).style.display = '';

		}

	},

	hide : function() {

		for ( i=0; i < arguments.length; i++ ) {

			$(arguments[i]).style.display = 'none';

		}

	}

};

Leave a Reply

Your email address will not be published. Required fields are marked *