17
loading...
This website collects cookies to deliver better user experience
body
element, we need to add a button
that changes the background color whenever we click on it.<main>
<p>
The Color Used Is <br><span class="color">rgb(255, 255, 255)</span>
</p>
<button class="change">
Generate
</button>
</main>
main{
text-align: center;
font-family: sans-serif;
}
body{
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
p{
border: 3px solid Black;
margin-bottom: 2rem;
padding: 1rem;
}
.change{
padding: .7em 1em;
font: bold 1.2rem sans-serif;
border: 3px solid #000;
cursor: pointer;
}
.color{
font-weight: bold;
text-decoration: underline;
}
you may think or write a different code ... it doesn't matter ... it only have to make the job done
//select the span
const colorName = document.querySelector(".color");
//select the button
const changeBtn = document.querySelector(".change")
//create the function
function changeColor() {
//creating three random numbers
let r = Math.floor(Math.random() * 256)
let g = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
//create a template literal string rgb color based on the previous numbers and store it on a color variable
let color = `rgb(${r}, ${g}, ${b})`
//change the body's background color to the new generated color and also show it the span text content
document.body.style.backgroundColor = color;
colorName.textContent = color
}
//we call the changeColor function every time we click on the button
changeBtn.addEventListener("click", changeColor)
rgb
css function to create color, we know that this function accept 3 parameters as numbers between 0 and 255Math.random()
returns number between 0 and 1 but without including 1 then Math.random() * 256
will return a number between 0 and 256 without including 256 but it will be a decimal number here it comes the