Hello,

What I am trying to do is show or hide a div when a user clicks the link, but I have multiple divs that belong in the same place so when the user clicks a link it needs to hide the current div, if there is one, and then show the new one. I have tried a variety of code and I am rather new to Javascript.

I've tried this way:

function showElement(layer){
	var myLayer = document.getElementById(layer);
	
	if(myLayer.style.display=="none"){
		myLayer.style.display="block";
		myLayer.backgroundPosition="top";
		var changeddiv = document.getElementById(layer);
	}
		
		if(chageddiv == 'sub_cat_1') {
			document.getElementById('sub_other_services').style.display="none";
			document.getElementById('sub_other_services').backgroundPosition="top";
			document.getElementById('sub_about_us').style.display="none";
			document.getElementById('sub_about_us').backgroundPosition="top";
			document.getElementById('sub_comp_info').style.display="none";	
			document.getElementById('sub_comp_info').backgroundPosition="top";
			document.getElementById('sub_cat_2').style.display="none";	
			document.getElementById('sub_cat_2').backgroundPosition="top";
		}

and this way:

function showElement(layer){
	var myLayer = document.getElementById(layer);
	
	if(myLayer.style.display=="none"){
		myLayer.style.display="block";
		myLayer.backgroundPosition="top";
    }
		
		if(document.getElementById('sub_other_services').style.display=="block") {
			document.getElementById('sub_cat_1').style.display="none";
			document.getElementById('sub_cat_1').backgroundPosition="top";
			document.getElementById('sub_about_us').style.display="none";
			document.getElementById('sub_about_us').backgroundPosition="top";
			document.getElementById('sub_comp_info').style.display="none";	
			document.getElementById('sub_comp_info').backgroundPosition="top";
			document.getElementById('sub_cat_2').style.display="none";	
			document.getElementById('sub_cat_2').backgroundPosition="top";
		}

and both were to no avail. Any help would be much appreciated.

Chuffman,

Try this:

function showElement(divID){
	var divIDs = [ 'sub_other_services', 'sub_about_us', 'sub_comp_info', 'sub_cat_1', 'sub_cat_2' ];//Array of divsIDs in the group
	for(var i=0; i<divIDs.length; i++){//loop through the array
		document.getElementById(divIDs[i]).style.display = (divIDs[i] == divID) ? 'block' : 'none';//show the required div, and hide all the others
	}
}

For explanation, see comments in code.

Airshow

This question has already been answered. Start a new discussion instead.