Question

I am trying to toggle some text, Q & A style with the question as a button that will display its answer when clicked. It functions fine when the CSS does not load the page with target element set to display:none
However, I want the element to be hidden by default until the button is clicked. For some reason, the js function does not work when the page is loaded in this manner. Anyone know why?

HTML

<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="sample.css" media="screen" />
    <script src="toggle.js" type="text/javascript"></script>
</head>
<body>
    <button type="submit" class="question" id="q1" onclick="toggle_visibility('q1')">
        This is my question?
    </button>
    <div class="dynamic-text-wrapper">
        <div class="answer" id="a1">
            Here is the answer to your question.
        </div>
    </div>
</body>
</html>

CSS

.dynamic-text-wrapper {height: 25px;}
.answer {
    height: 25px;
    display: none; /*DOESN'T WORK WHEN THIS LINE IS INCLUDED.  But I want to not displayed to be default*/}

JavaScript

function toggle_visibility(questionID) {
var targetElement = document.getElementById('a'+parseInt(questionID.substring(1))); 
    if(targetElement.style.display == '') {
        targetElement.style.display = 'none';
    }
    else {
        targetElement.style.display = '';
    }}
Was it helpful?

Solution

Instead of

targetElement.style.display = '';

you've got to write

targetElement.style.display = 'block';

In the 'if', you've got to check if you've established the display to block. If you haven't, the elment will be invisible (as set by the CSS rule):

if (targetElement.style.display == 'block') { 

If you set display: none in CSS, doing .style.display = '' means that you're 'erasing' the inline value (which takes precedence over the value in a CSS file). So, by doing this, the new value for display will be 'none', as set in the CSS. By setting it to 'block', the final value of display is block.

I suggest you to read something about how CSS rules are applied.

OTHER TIPS

Option 1

Use

.answer {
    display: none; /* Hide by default */
}

and

targetElement.style.display = targetElement.style.display ? '' : 'block';

That is, if targetElement.style.display is falsy (you haven't set it, so it's hidden by default), you set it to 'block'. And if it is truthy (you have set it to 'block'), you clear it.

Option 2

This option will make your function reusable with non-block elements.

Use

<div class="answer default-hidden" id="a1"></div>

And, at onload, run

var els = document.getElementsByClassName('default-hidden');
for(var i=0, l=els.length; ++i) els[i].style.display = 'none';

And in your function:

targetElement.style.display = targetElement.style.display ? '' : 'none';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top