views:

478

answers:

2

I have a html page with a basic tab control. I use javascript to show and hide tabs and tab content divs. My problem is that if I change the visibility of an element inside one of the tab content divs to 'hidden', then back to 'visible', the element seems to forget or lose its parent div container and remains visible, regardless of its original parents visibility.

To illustrate, take the following example:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
     "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head>
<script type="text/javascript"> 
    function hideTab(){
        document.getElementById('tab1').style.visibility = 'hidden'
    }
    function showTab(){
        document.getElementById('tab1').style.visibility = 'visible'
    }
    function hideContent(){
        document.getElementById('tc1').style.visibility = 'hidden'
    }
    function showContent(){
        document.getElementById('tc1').style.visibility = 'visible'
    }
</script>
</head>
<body>
    <a href="javascript: hideTab()">Hide Tab</a><br />
    <a href="javascript: showTab()">Show Tab</a><br />
    <a href="javascript: hideContent()">Hide Content</a><br />
    <a href="javascript: showContent()">Show Content</a><br /><br />
    <div id="tab1" style="background:yellow;width:100px">
        <div id='tc1'>Content Text</div>
    </div>
</body>
</html>

In IE8 click 'Hide Tab' then 'Show Tab' this works ok. With the tab shown click 'Hide Content' then 'Show Content' This is also correct. Now click 'Hide Tab' again and you should see the tab disappear but the content incorrectly remains.

In IE8, the problem disappears when I use compatibility mode. Also, I have noticed that if I remove DOCTYPE element, I can't replicate the problem.

In Chrome (my personal favourite) the problem is persistent regardless of the DOCTYPE element. I haven't tried this in firefox.

I'm sure there is a very good reason for this behaviour, I'm also sure that there will be a simple solution for me to make my tabs work correctly. I look forward to your comments.

+1  A: 

Instead of setting the child element's visibility to 'visible', set it to 'inherit' -- then it will obey its parents visibility setting instead of overriding it independently.

Eric Kolb
+4  A: 

This is because the CSS property 'visibility' is inherited, but does not affect the layout of the page. Therefore, if you set an element to be hidden, all its children will be, unless you explicitly make them visible (which is the case by specifying visibility: visible).

You must reset the CSS property to be inherited to get the behavior you want. You can do so by using the inherit keyword as the value: visibility: inherit

EDIT Or, as Javascript:

element.style.visiblity = 'inherit';
zneak
zneak - Thanks very much, this solved my problem. As you advised, I set each element to 'inherit' after changing to 'visible' and the problem is fixed. Thank you.
Fly_Trap