Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing background color with every click in Pure Javascript

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;
}
like image 630
nishkaush Avatar asked Dec 29 '16 05:12

nishkaush


2 Answers

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>
like image 65
ab29007 Avatar answered Sep 19 '22 09:09

ab29007


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

like image 26
user247217 Avatar answered Sep 21 '22 09:09

user247217