Page 1 of 1

Show Layer / Hide all others

Posted: Wed Mar 08, 2006 10:03 pm
by SBro
My experience with javascript is quite limited, but I'm trying to write a piece of code that shows a layer when a checkbox is clicked, and hides all other layers, here is my (incorrect) code. I can get it to show / hide the layers fine, but as for hiding all other layers (all layer id's are contained in the boxes array) I can't get it to do this, any help would be appreciated, thanks.

Code: Select all

function showMe(id, chk) {
	var obj = document.getElementById(id), boxes = ["modu5", "modu112", "modu4", "modu1", "modu14", "modu11", "modu10", "modu13"];
	document.getElementById(boxes[1]).style.display = "block";
	if (chk.checked==true) {
		for (var n = 1; n < boxes.length; n++) {
			var ob = document.getElementById(boxes[n]);
			ob.style.display = "none";
		}
		obj.style.display = "block";
	} else {
		obj.style.display = "none";
	}
}

Different Loop?

Posted: Fri Mar 17, 2006 7:19 pm
by tomprogers
You may want to try doing this slightly differently. Here's an idea:

Code: Select all

// handy for checking to see if a supplied thing is a member of a list
if(typeof Array.prototype.find == 'undefined')
	Array.prototype.find = function(needle){
	for(i=0; i < this.length; i++)
		if(this[i] == needle) return i;
	return false;
	}

// set to visible objects whose ids were passed, all not on the list should be hidden
function setVis(ids)
{	// ids is an array containing the IDs of the objects you want to show; everything else should be hidden
	boxes = new Array("modu5", "modu112", "modu4", "modu1", "modu14", "modu11", "modu10", "modu13");
	for(i = 0; i < boxes.length; i++)
	{
		if(ids.find(boxes[i]))
			document.getElementById(boxes[i]).style.display = ";";
		else
			document.getElementById(boxes[i]).style.display = "none";
	{
	return true;
}
This code expects that you have previously prepared a list of things that should be visible, which is, I think, better encapsulation.

Assuming you have three divs, each of which has a "hide me" checkbox, checking that box would call some other function, perhaps written like so:

Code: Select all

function addToHide(oCB)
{
	if(!oCB) return false;
	if(!oCB.checked) return false;
	aVisPrefs = window.myApp.visibilityPrefs;
	if(aVisPrefs.find(oCB.value) == -1)
	{
		aVisPrefs.push(oCB.value);
		setVis(aVisPrefs);
	}
	return true;
}
NOTE - Some browsers do not have native support for the Array.push() method, so if you settle on some variation of this script that uses it, you'll want to define one, similar to my Array.find() method definition.

If you have further questions, let me know.