Linking to a section of a site that is hidden by a hide/show JavaScript function

Posted by hollyb on Stack Overflow See other posts from Stack Overflow or by hollyb
Published on 2010-04-29T21:01:29Z Indexed on 2010/04/29 21:07 UTC
Read the original article Hit count: 186

Filed under:
|
|

I am using a bit of JavaScript to show/hide sections of a site when a tab is clicked. I'm trying to figure out if there is a way I can link back to the page and have a certain tab open based on that link.

Here is the JS:

   var ids=new Array('section1','section2','section3','section4');

function switchid(id, el){  
    hideallids();
    showdiv(id);

    var li = el.parentNode.parentNode.childNodes[0];
    while (li) {
        if (!li.tagName || li.tagName.toLowerCase() != "li")
            li = li.nextSibling; // skip the text node
        if (li) {
          li.className = "";
          li = li.nextSibling;
        }
    }
    el.parentNode.className = "active";
}

function hideallids(){
    //loop through the array and hide each element by id
    for (var i=0;i<ids.length;i++){
        hidediv(ids[i]);
    }         
}

function hidediv(id) {
    //safe function to hide an element with a specified id
        document.getElementById(id).style.display = 'none';
}

function showdiv(id) {
    //safe function to show an element with a specified id        
        document.getElementById(id).style.display = 'block';
}

And the HTML

<ul>
<li class="active"><a onclick="switchid('section1', this);return false;">One</a></li>
<li><a onclick="switchid('section2', this);return false;">Two</a></li>
<li><a onclick="switchid('section3', this);return false;">Three</a></li>
<li><a onclick="switchid('section4', this);return false;">Four</a></li>
</ul>

<div id="section1"  style="display:block;">   
<div id="section2" style="display:none;">  
<div id="section3" style="display:none;">  
<div id="section4" style="display:none;">

I haven't been able to come up with a way to link back to a specific section. Is it even possible with this method?

Thanks!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about linking