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>
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 ?##
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With