troubleshooting Question

Javascript to open and close Divs one at a time

Avatar of Robert Granlund
Robert GranlundFlag for United States of America asked on
JavaScriptHTMLPHP
4 Comments1 Solution271 ViewsLast Modified:
I have the following script.  It closes and opens Divs onClick.  However, I want only one Div open at a time. If I click on the first link, it opens and if I click on the second link it opens also. Here is what I have:

<script>
function showOrHide(linkElem)
{
        var rel = linkElem.getAttribute('rel');
        var divElem = document.getElementById(rel);
        var divGrp = divElem.getAttribute('name');
        var aInGrp = document.getElementsByTagName('A');
        var divInGrp = document.getElementsByTagName('DIV');

        // reset all elements in the same group
        for (i = 0; i < aInGrp.length; i++)
        {
                elm = aInGrp[i];
                if (elm.getAttribute('collapsible') == "yes" && elm.getAttribute('rel') != rel)
                {
                        elm.innerText = 'Expand';
                }
        }
        for (i = 0; i < divInGrp.length; i++)
        {
                elm = divInGrp[i];
                if (elm.getAttribute('collapsible') == "yes" && (elm.getAttribute('id') != rel))
                {
                        elm.style.display = 'none';
                }
        }

        if (divElem.style.display == 'none')
        {
                divElem.style.display = 'block';
                linkElem.innerText = "Collapse";
        }
        else
        {
                divElem.style.display = 'none';
                linkElem.innerText = "Expand";
        }
}
</script>


<ul>
<li class="text"><a href="#" style="collapsible:yes;" name="portfolio" rel="galleryFenderCont" onclick="showOrHide(this, 'galleryFenderCont');return false;">AAA</a><br /></li>
			
<li class="text"><a href="#" style="collapsible:yes;" name="portfolio" rel="gallerySteinCont" onclick="showOrHide(this, 'gallerySteinCont');return false;">BBB</a><br /></li>
</ul>


<div id="galleryFenderCont" name="portfolio" style="display:none;collapsible:yes;">
CONTENT HERE
</div>

<div id="gallerySteinCont" name="portfolio" style="display:none;collapsible:yes;">
CONTENT HERE
</div>
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros