Changing background color with every click in Pure Javascript
Asked Answered
S

3

7

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;
}
Sophrosyne answered 29/12, 2016 at 5:2 Comment(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.Tanto
R
11

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>
Roble answered 29/12, 2016 at 5:6 Comment(2)
Please explain why this changes is needed (I know why, but code-only answer's aren't the greatest).Justle
@AlexanderO'Mara Thank you for that, I just added it.Roble
T
3

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 ?##

Telemeter answered 29/12, 2016 at 5:13 Comment(0)
S
0
// 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
})
Spraggins answered 4/3, 2022 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.