Reputation: 83
I am trying to change the background color of the wrapper every time I click the button. When it is clicked, it is supposed to change to a random color that is in the array. Any thoughts for a beginner? Also the CSS was done with SASS so it may not look pretty.
function change_Color() {
var color = ["blue", "red", "green", "yellow"];
document.getElementById("wrapper").style.backgroundColor = color;
}
body {
margin: 0;
}
* {
box-sizing: border-box;
}
#wrapper {
width: 100%;
height: 100vh;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
button {
padding: 10px;
background: orange;
color: white;
border: none;
border-radius: 10px;
font-size: 2rem;
transition: .5s ease;
&:hover {
box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
cursor: pointer;
}
&:focus {
outline: 0;
color: skyblue;
}
}
}
<div id="wrapper">
<button onclick="change_Color()">Click me!</button>
</div>
Upvotes: 1
Views: 231
Reputation: 579
Check this one. I merged body and wrapper in CSS and I gave id for body
var colors = ["red", "blue", "green", "yellow"];
function changeColor() {
document.getElementById("body").style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];}
#body {
margin: 0;
box-sizing: border-box;
width: 100%;
height: 100vh;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
button {
padding: 10px;
background: orange;
color: white;
border: none;
border-radius: 10px;
font-size: 2rem;
transition: .5s ease;
&:hover {
box-shadow: 0 4px 3px 0px rgba(255, 255, 255, 0.8);
cursor: pointer;
}
&:focus {
outline: 0;
color: skyblue;
}
}
<body id='body'>
<button onclick="changeColor();">Click me!</button>
</body>
Upvotes: 0
Reputation: 33
You should try this:
function changeBackground(color) {
document.body.style.background = color;
}
window.addEventListener("load",function() { changeBackground('red') });
instead of:
function change_Color() {
var color = ["blue", "red", "green", "yellow"];
document.getElementById("wrapper").style.backgroundColor = color;
}
Upvotes: 1
Reputation: 336
You can use math.random() to choose random color from your array.
Upvotes: 1
Reputation: 301
To pick a random color just use the Math.random()
function:
var colors = ["blue", "red", "green", "yellow"];
var color = colors[Math.floor(Math.random() * colors.length)]
document.getElementById("wrapper").style.backgroundColor = color;
Upvotes: 1