skip to Main Content

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


  1. looks like its an duplication of:
    Is this an even or odd element?

    Therefor the following Code should work for you.

    $('div').each(function(i, el) {
       // As a side note, this === el.
       if (i % 2 === 0) { /* we are even */ }
       else { /* we are odd */ }
    });
    
    Login or Signup to reply.
  2. The parameter you pass in the $.each is the array and the function callback with index and value

    $.each([ 52, 97 ], function( index, value ) {
      alert( index + ": " + value );
    });
    

    So in your case you can check even odd for your index and add the class accordingly.

    Something like this

    $.getJSON("XXXXYYYY.json", function (data) {
        var html = '';
        $.each(data, function (index, value) {
            html += index%2===0 ? '<div class="container right">' : '<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);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search