I have a php page with spoilers in wich I use javascript to view or hide the spoilers. This is done by changing classes on the span of each spoiler div (.hidden, .visible). The classes are s1, a1, s2, a2, s3, a3 etc.
I want to select each spoiler and give them an onclick function to view or hide the answer of the clicked spoiler. This can be done which variables in a for loop. I am getting no errors in Chrome debugger, but the classes won't change.
It works fine without the for loop.
This is a part of my php:
<div class="spoiler">
Is this a second question
<a href="#" id="s1">View answer</a>
<span id="a1" class="hidden">Yes it is</span>
<hr />
</div>
<div class="spoiler">
Is this a second question
<a href="#" id="s2">View answer</a>
<span id="a2" class="hidden">Yes it is</span>
<hr />
</div>
This is my javascript using jquery:
window.onload = function () {
for (var i = 1; i < 2; i++) {
var s = [];
s[i] = document.getElementById("s" + i);
s[i].addEventListener("click", function () {
var a = [];
a[i] = document.getElementById("a" + i);
if ($("a" + i).hasClass("hidden")) {
$("a" + i).removeClass("hidden");
$("a" + i).addClass("visible");
$("a" + i).html("Hide answer");
} else if ($("a" + i).hasClass("visible")) {
$("a" + i).removeClass("visible");
$("a" + i).addClass("hidden");
$("a" + i).html("View answer");
}
}, true);
};
}
Thanks for the help!