When the button div is clicked I would like to change the body to a random color in the "colors" array. This code works, but it only works the first time I click. What can I change for the body to change color EVERY time the div is clicked?
var colors = ["#3b609b", "#9b3b3b", "#3b9b81", "#7da5a4"];
var rand = Math.floor(Math.random() * colors.length);
$(".button").click(function() {
$("body").css("background-color", colors[rand]);
})
In your code, the value of
rand
variable remains same for every click.
You will need to update this value in each click so put this line of code var rand = Math.floor(Math.random() * colors.length)
in click handler.
var colors = ["#3b609b", "#9b3b3b", "#3b9b81", "#7da5a4"]; $(".button").click(function() { var rand = Math.floor(Math.random() * colors.length); $("body").css("background-color", colors[rand]); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Gaurav</h1> <button class="button"> Change Color</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.