Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change the background color of div using jquery?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading