john john
john john

Reputation: 51

JQuery mixing with HTML

I am trying to read JSON data and print it in green or red color depending on the 'scoreChange' being greater or less then zero .

<script>
$.getJSON('/fetchTicker', function (data) {
    $.each(data.result, function () {
        $("#marqueecontent").append("<span"
        if (this['scoreChange'] >= 0){
            "style='color:#66FF13'>" + this['playerName']
                + " + " + this['scoreChange'] + " % " + "&nbsp;&#9650;&nbsp;";
        }else(this['scoreChange'] < 0){
          "style='color:#FF2020'>" + this['playerName']
                + this['scoreChange'] + " % " + "&nbsp;&#9660;&nbsp;";  
        }
                "&#x2758;&nbsp;&nbsp;</span>"

                );
    });
});
</script>

Upvotes: 0

Views: 36

Answers (2)

Michael M.
Michael M.

Reputation: 189

Or just create the object and set the css styles after:

<script>
var span = $('<span />').html(this['playerName'] + ' + ' + this['scoreChange'] + ' % &nbsp;&#9650;&nbsp;');

if (this['scoreChange'] >= 0) {
    span.css('color', '#66FF13');
} else {
    span.css('color', '#FF2020');
}

$("#marqueecontent").append(span);
</script>

Upvotes: 0

B. Desai
B. Desai

Reputation: 16436

Instead of using if inside append. Assign color value to variable before it. Then use it in append

<script>
$.getJSON('/fetchTicker', function (data) {
    $.each(data.result, function () {
        var colorToChange = "";
        if (this['scoreChange'] >= 0){
          colorToChange = "#66FF13";
        }
        else
        {
          colorToChange = "#FF2020";
        }
        $("#marqueecontent").append("<span style='color:"+colorToChange+"'>" + this['playerName']
                + " + " + this['scoreChange'] + " % " + "&nbsp;&#9650;&nbsp;&#x2758;&nbsp;&nbsp;</span>"

                );
    });
});
</script>

Upvotes: 1

Related Questions