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;
}
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. Commented Dec 29, 2016 at 6:00

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Please explain why this changes is needed (I know why, but code-only answer's aren't the greatest).
@AlexanderO'Mara Thank you for that, I just added it.
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 ?##

Comments

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
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.