I’m trying to generate a .html div containers using .json file that looks like below.
[ { "KEYWORD": XXXX, "DATEx": XXXX, "TOPIC": XXXX, "CSPANLINK": XXXX, "EXCERPTS": XXXX }, { "KEYWORD": YYYY, "DATEx": YYYY, "TOPIC": YYYY, "CSPANLINK": YYYY, "EXCERPTS": YYYY }]
For odd numbered elements, I want to create div with class = "container left" and for even numbered elements, I want to create div with class = "container right". I used the below code to generate .html:
$.getJSON("XXXXYYYY.json", function (data) {
var html = '';
$.each(data, function (key, value) {
html += '<div class="container left">';
html += '<div class="content">';
html += '<h2>' + value.DATEx + '</h2>'
html += '<p>' + value.EXCERPTS + '</p>';
html += '</div>';
html += '</div>';
});
$('div.timeline').html(html);
});
So in a nutshell, I would like to alternate between these two codes, depending on the index of each element.
html += '<div class="container left">';
and
html += '<div class="container right">';
What kind of javascript conditional statement should I use to do this?
2
Answers
looks like its an duplication of:
Is this an even or odd element?
Therefor the following Code should work for you.
The parameter you pass in the
$.each
is the array and the function callback withindex
andvalue
So in your case you can check even odd for your index and add the class accordingly.
Something like this