-1

I want to change the background color of div at runtime using jquery. The div is displaying but it's background color isn't changing. I don't know what is wrong with this code I have written.

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    </head>
    <body>
        <div id="color" style="width:100px;height:100px;background-color:grey;">Hello, world!</div>
        <script>
            function change_color()
            {
                r = floor(Math.random()*256);
                g = floor(Math.random()*256);
                b = floor(Math.random()*256);

                rgb = "rgb(" + r + ", " + g + ", " + b + ")";

                $("#color").css("background-color", rgb);
            }

            setInterval(change_color, 1000);
        </script>
    </body>
</html>

I want rgb values in decimal.

1 Answers1

5

You need to use Math.floor function and not floor (currently floor is not defined in your code and that's why your r g b values are not valid):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
    <div id="color" style="width:100px;height:100px;background-color:grey;">Hello, world!</div>

    <script>
        function change_color() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            var rgb_ = "rgb(" + r + ", " + g + ", " + b + ")";
            $("#color").css("background-color", rgb_);
        }

        setInterval(change_color, 1000);
    </script>
</body>
</html>

With this correction, the setInterval should now work as intended, and the background color of the div with id "color" will change every second.

xdevs23
  • 3,824
  • 3
  • 20
  • 33
Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53