0

I'm trying to do a conditional formatting for the $row->cap24hrChange results. If it's < 0, I want the value to be colored red, otherwise it should be green. I'm not getting any response from the script.

<table><head><style>
td {text-align: right;}
</style></head><table>
    <thead>
        <tr>
            <th>#Rank</th>
            <th>Name</th>
            <th>Price</th>
            <th>Mkt Cap</th>
            <th>Volume</th>
            <th>Supply</th>
            <th>24h(%)</th>
        </tr>
    </thead>
    <tbody>
        <?php function compare($a, $b) {
            return intval($a->position24) - intval($b->position24);
        } 

        $json = file_get_contents('http://www.coincap.io/front');
        $data = json_decode($json);
        usort($data, 'compare'); 
        ?>
        <?php foreach ($data as $row) { ?>
        <tr>
            <td><?= $row->position24; ?></td>
            <td><?= $row->long; ?></td>
            <td><?= number_format($row->price, 4); ?><\td>
            <td><?= number_format($row->mktcap, 2); ?><\td>
            <td><?= number_format($row->volume, 2); ?><\td>
            <td><?= number_format($row->supply, 2); ?><\td>
            <td><?= $row->cap24hrChange; echo "<script type=\"text/javascript\"> var trTags = document.getElementsByTagName("td"); for (var i = 0; i < trTags.length; i++) { var tdEightEl = trTags[i].children[7]; if (tdEightEl.innerText < 0) {tdEightEl.style.color = "red"; } else if (tdEightEl.innerText > 0) {tdEightEl.style.color = "green"; } }</script>";?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>

EDIT

On a very related note: how could I work around that code so as to include icons on the right (↑ and ↓) for values >0 and <0, respectively?

EDIT(2)

I figured it out with the help of $foo = "bar".$foo

<td style="color:<?php if($row->cap24hrChange > 0){ echo "green"; $row->cap24hrChange = $row->cap24hrChange . " 🠙 ";}else if($row->cap24hrChange < 0){ echo "red"; $row->cap24hrChange = $row->cap24hrChange . " 🠛 ";}?>"><?= $row->cap24hrChange;?></td>

1 Answer 1

1

Don't use javascript to do that. It's something you can know at the before page load so you can put it in static.

<td style="color:<?php if($row->cap24hrChange > 0){ echo "green"; }else if($row->cap24hrChange < 0){ echo "red"; }?>"><?= $row->cap24hrChange;?></td>

But be careful you don't have the case $row->cap24hrChange == 0 in your code.

Sign up to request clarification or add additional context in comments.

1 Comment

That's really neat! Thanks =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.