Home > database >  How to change text color using javascript function?
How to change text color using javascript function?

Time:05-02

I'm trying to change text color depending on the number value.

<script>
function change_color_text (num1) {
 var rate_num = num1;
 if(rate_num >= 7) {
    rate_num.style.color = "#008000"; // green
 } else if (rate_num >= 4) {
    rate_num.style.color = " #FFFF00"; // yellow
 } else {
    rate_num.style.color = " #FF0000"; // red
 }
 return rate_num;
}
</script>

And after the function, I'm doing like

<?php echo "<script> change_color($sum); </script>"?>

The "$sum" is just my variable. I'm newbie to JS and PHP so maybe all the code would be wrong. Sorry about that.

CodePudding user response:

This code will definitely give an error, "cannot read value of undefined"

This has to do with DOM manipulation. In this code, JavaScript engine doesn't understand what element style color you're trying to change.

A way to fix this will be

const rate_num = document.querySelector(".class")

Where .class is the class name of whatever text you're trying to change in the HTML.

CodePudding user response:

you can write this

     <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div id="demo"></div>
    <script>
    function change_color_text (num1) {
    var rate_num = num1;
    if(rate_num >= 7) {
        document.getElementById('demo').innerHTML="green";
        document.getElementById('demo').style.color="green";
    } else if (rate_num >= 4) {
        document.getElementById('demo').innerHTML="yellow"; // yellow
        document.getElementById('demo').style.color="yellow";
    } else {
        document.getElementById('demo').innerHTML="red" // red;
        document.getElementById('demo').style.color="red";
    }
    return rate_num;
    }

    </script>
    </body>
    </html>


    <?php echo "<script> change_color_text(8) </script>"?>
  • Related