I’ve made a little accordion-like script. Technically it works, but on the second click. How to fix it?
<ul>
<li>chapter 1</li><span>lorem ipsum</span>
<li>chapter 2</li><span>lorem ipsum</span>
<li>chapter 3</li><span>lorem ipsum</span>
<li>chapter 4</li><span>lorem ipsum</span>
<li>chapter 5</li><span>lorem ipsum</span>
</ul>
var a = document.getElementsByTagName('li');
for (var i = 0; i < a.length; i++) {
a[i].onclick = function() {
var st = this.nextSibling.style;
if (st) {
st.display = (st.display == "none" ? "block" : "none");
}
};
}
st.displaystarts out empty because it’s set in CSS and not in an inline style. There are three ways to fix this.(1) Explicitly set the style in javascript ahead of time:
Fiddle: http://jsfiddle.net/YcEjF/1/
(2) Test on “block” instead of “none”, reversing the comparison, but otherwise using the same method:
Fiddle: http://jsfiddle.net/YcEjF/2/
(3) Explicitly set the style tags instead of using css. So leave your javascript the same but change your html, like so:
And remove that
display: none;from the css:Fiddle: http://jsfiddle.net/YcEjF/3/