I have following html with css style and js:
<p>This is a text
<br />
<a ref="##" onclick="showHideBlocks('i1', 'i2')">
<span id="i1" class="show">(show more)</span>
</a>
</p>
<p id="i2" class="hidden">This is hidden text
<br />
<a ref="##" onclick="showHideBlocks('i1', 'i2')">(hide me)
</a>
</p>
and my css:
.show {
display: block;
}
.hidden {
display: none;
}
In web view: this shows like this as expected.
This is a text
(show more)
and here is the js function:
function showHideBlock(id)
{
var e = document.getElementById(id);
var display = e.style.display;
console.log(typeof display)
console.log(display)
if (display === 'block') {
display = 'none';
} else {
display = 'block';
}
e.style.display = display;
}
function showHideBlocks(id1, id2)
{
showHideBlock(id1);
showHideBlock(id2);
}
First time, I click on "(show more)", the hidden block is displayed, partially as expected:
This is text
(show more)
This is hidden text
(hide me)
However, the text "(show more)" is still displayed, expected hidden! This is expected:
This is text
This is hidden text
(hide me)
Then, I click on "(hide me)", the text "(show more)" and the next paragraph are all hidden. That means the subsequently calls are working (since display are assigned by string 'block' or 'none').
This is text
I have added log message to the js function. I notice that for the first time, display is string type but value is empty!(the second line should be empty, I use "" to emphasize the empty)
string
""
How can I get its property as "block" or "none" for the first time?
Thanks @AnhPC03 for correction. But the problem is still the same. I have updated codes in the question. Actually the above codes are simplified from my project.
style.displaywill only show the value found in thestyleattribute - not the actual display value. If you don't specifystyle="display:block"to start with - this code does not work as you are only showing if it is set tonone. You could change the if statement toif(display === "block" || display === ""){as long as you aren't hiding via CSS.style="display:block"whereas on your original code, you are not.