I am trying to make a button in Javascript which when clicked, changes the background color to a random color.
My code runs fine on the first click but doesn't work on subsequent clicks.
What can I do to fix this in pure javascript, without any jquery. Thanks!
var buton=document.getElementById("buton");
var randcol= "";
var allchar="0123456789ABCDEF";
buton.addEventListener("click",myFun);
function myFun(){
for(var i=0; i<6; i++){
randcol += allchar[Math.floor(Math.random()*16)];
}
document.body.style.backgroundColor= "#"+randcol;
}
I am trying to make a button in Javascript which when clicked, changes the background color to a random color.
My code runs fine on the first click but doesn't work on subsequent clicks.
What can I do to fix this in pure javascript, without any jquery. Thanks!
var buton=document.getElementById("buton");
var randcol= "";
var allchar="0123456789ABCDEF";
buton.addEventListener("click",myFun);
function myFun(){
for(var i=0; i<6; i++){
randcol += allchar[Math.floor(Math.random()*16)];
}
document.body.style.backgroundColor= "#"+randcol;
}
Share
Improve this question
asked Dec 29, 2016 at 5:02
nishkaushnishkaush
1,5481 gold badge14 silver badges21 bronze badges
1
-
1
All of the answers are insane, just generate a random color like
'#' + Math.random() * 0xFFFFFF
and that's it, I don't understand what is all this allchar and loop for. – Azamantes Commented Dec 29, 2016 at 6:00
3 Answers
Reset to default 11The problem is that you are not resetting the randcol
once executing. You keep adding to the previous value, hence first time it is a valid color code but next time it is not a valid color code.
So reset your randcol
to an empty string before you execute your for
loop
var buton=document.getElementById("buton");
var allchar="0123456789ABCDEF";
buton.addEventListener("click",myFun);
function myFun(){
var randcol= "";
for(var i=0; i<6; i++){
randcol += allchar[Math.floor(Math.random()*16)];
}
document.body.style.backgroundColor= "#"+randcol;
}
<button id="buton">click me</button>
Try below its working i will test it.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function myFun(){
var randcol= "";
var allchar="0123456789ABCDEF";
for(var i=0; i<6; i++){
randcol += allchar[Math.floor(Math.random()*16)];
}
document.body.style.backgroundColor= "#"+randcol;
}
</script>
</head>
<body>
<button onclick="javascript:myFun()">Change color</button>
</body>
</html>
## can we saved color to localstorage ?##
// easy option
let btnChange = document.querySelector(".btnColorChange")
let showColorName = document.querySelector(".colorName")
btnChange.addEventListener("click", function(){
let color = '#';
//create random number and small the number with slice concat with color = #
color += random = Math.random().toString(16).slice(2,8);
// select the body tag
document.body.style.backgroundColor = color
// show the color name in screen
showColorName.innerHTML = color
})