Changer la couleur d'une div aléatoirement

Par cochi69, il y a 10 ans


Bonjour

j'ai créer une page web sur laquelle il y a un carré. Et j'aimerais qu'à chaque clic sur le carré, sa couleur change aléatoirement

J'ai donc fait 2 fonctions :

function changeBackgroundColor(color){ document.getElementById("carre").style.backgroundColor = color; }

et

function randColor(){ return '#'+(function(h){return new Array(7-h.length).join("0")+h})((Math.random()*(0xFFFFFF+1)<<0).toString(16)); ; }

donc si je mets :

<div onclick="changeBackgroundColor('#fff');"id="carre" style="width:220px; height:220px; " >

dans mon code html, et que je clique sur le carré, sa couleur passe de noire à blanche. C'est un bon début, mais ce n'est pas vraiment ce que je veux obtenir

J'ai donc essayé ça :

<div onclick="changeBackgroundColor('randColor()');"id="carre" style="width:220px; height:220px; " > </div>

mais ça ne fonctionne pas

Auriez vous une piste pour résoudre mon problème ?

Merci d'avance

2 réponses

sizo0, il y a 10 ans

Enlève les quotes autour de randColor()

<div onclick="changeBackgroundColor(randColor());" id="carre" style="width:220px; height:220px; "></div>

EDIT:
Si tu veux que la solution fonctionne pour tout carré indépendemment de son id.

function changeBackgroundColor(self, color){ self.style.backgroundColor = color; } <div onclick="changeBackgroundColor(this, randColor());" id="carre" style="width:220px; height:220px;"></div>
cochi69, il y a 10 ans

Super merci énormément