Changing the background color with every click in Pure Javascript

I am trying to make a button in Javascript that when clicked changes the background color to a random color.

My code works fine on the first click, but doesn't work on subsequent clicks.

What can I do to fix this in pure javascript without 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; } 
+6
source share
2 answers

The problem is that you are not restarting randcol after execution. You continue to add to the previous value, so the first time it is a valid color code, but the next time it is not a valid color code.

So, reset your randcol to an empty string before doing the 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> 
+7
source

Try below his work, I will check 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> 
+2
source

Source: https://habr.com/ru/post/1013591/


All Articles