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;
}
The 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>