I want to change the background color of a div at runtime using jquery. The div is showing but its background color is not changing. I don't know what's wrong with the code I wrote.
<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 = Math.floor(Math.random()*256); g = Math.floor(Math.random()*256); b = Math.floor(Math.random()*256); rgb_ = "rgb(" + r + ", " + g + ", " + b + ")"; $("#color").css("background-color", rgb_); } setInterval(change_color, 1000); </script> </body> </html>
I want decimal rgb value.
P粉8541192632023-09-17 20:45:11
You need to use the Math.floor
function instead of floor (floor is not defined in the current code, that's why your r g b values are invalid):
<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>