KolaCaine
KolaCaine

Reputation: 2187

Using randomly hex color, not the same value with a true generator

I created a function with vueJS for random hexadecimal color, but if I pick the output of my function, and I put the output on the generator of W3C for example (Link : HERE)

The function does not really work

So I hope to see the problem, because it's very disabling because I can't have a true value of Hex Color.

let random = function () {

  let text = "";
  const possible = "ABCDEF0123456789";

  for (var i = 0; i < 6; i++)
  text += possible.charAt(Math.floor(Math.random() *                               possible.length).toString(16));
     
  return '#' + text

}

const section = document.querySelector('section');
const title = document.querySelector('h1')

section.style.backgroundColor = random();
title.textContent = random();
section {
  width: 50px;
  height: 50px;
}
<section></section>
<h1></h1>

Upvotes: 2

Views: 251

Answers (3)

Durga
Durga

Reputation: 15604

let random = function () {

  let text = "";
  const possible = "ABCDEF0123456789";

  for (var i = 0; i < 6; i++)
  text += possible.charAt(Math.floor(Math.random() *                               possible.length).toString(16));
     
  return '#' + text

}

const section = document.querySelector('section');
const title = document.querySelector('h1')
var randomColor = random(); //get the color
section.style.backgroundColor = randomColor;
title.textContent = randomColor;
section {
  width: 50px;
  height: 50px;
}
<section></section>
<h1></h1>

Its because you are calling random function two time(section.style and title.textContent), call it once and store the value and use it, where you want.

Upvotes: 1

Caspar Kleijne
Caspar Kleijne

Reputation: 21864

A simple

section.style.backgroundColor = "#" + Math.floor(Math.random() * 16777215).toString(16);

is enough code

where 16777215 is #FFFFFF in decimal and toString(16) creates a hexadecimal variant. Read more; Number.prototype.toString():

Upvotes: 2

pim
pim

Reputation: 220

You're calling the random function twice, one for the text display, and once for the color square, so they're not mathching.

Here is a fix :

let random = function () {

  let text = "";
  const possible = "ABCDEF0123456789";

  for (var i = 0; i < 6; i++)
  text += possible.charAt(Math.floor(Math.random() *                               possible.length).toString(16));
     
  return '#' + text

}

const section = document.querySelector('section');
const title = document.querySelector('h1')

const color = random();
section.style.backgroundColor = color;
title.textContent = color;
section {
  width: 50px;
  height: 50px;
}
<section></section>
<h1></h1>

Upvotes: 1

Related Questions