JavaScript/jQuery newbie here... I am working towards looping through a JSON file and succesively render top-level items using jQuery. The aim here is to display individual elements and then fade them out before display successive ones. However, my script only renders the last element. Any idea what it is I could be doing wrong here?
JSON file---x.json
{"questions":[
{
"q":"Question1...?",
"a": [
"Answer 1a",
"Answer 1b",
"Answer 1c",
"Answer 1d"
]
},
{
"q":"Question2...?",
"a": [
"Answer 2a",
"Answer 2b",
"Answer 2c",
"Answer 2d"
]
}
]}
JavaScript file---x.js
$(document).ready( function () {
$.getJSON('x.json', function (jsondata) {
// compute total number of questions in JSON file
var totalQuestions = jsondata.questions.length;
$.each(jsondata.questions, function (i) {
var questionNumber = i + 1; // add one since indicies start at 0
var questionContent = jsondata.questions[i]["q"];
var answerContent = '';
// generate questions progress HTML text
var questionHTML = '<div class="questionCount">Question <span class="current">' + questionNumber +'</span> of <span class="total">' + totalQuestions + '</span>';
// generate question HTML text
questionHTML += '</div><h3>' + questionNumber + '. ' + questionContent + '</h3>';
console.log(JSON.stringify(jsondata.questions[i]["q"]));
var answersHTML = '<ul type="A" class="answers">';
$.each(jsondata.questions[i]["a"], function (k) {
answerContent = jsondata.questions[i]["a"][k];
answersHTML += '<li><input type="radio"><label>' + answerContent + '</label></li>';
});
answersHTML += '</ul></li>';
questionHTML += answersHTML;
console.log(questionHTML);
$("#placeholder").html(questionHTML);
setInterval(function () {
$("#placeholder").html(questionHTML);
$("#placeholder").fadeIn(6000).delay(3000).fadeOut(1000);
}, 5000);
});
});
});
HTML file---x.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JSON Sample</title>
</head>
<body>
<div id="placeholder"></div>
<script src="js/jquery.js"></script>
<script src="x.js"></script>
</body>
</html>