-2

I'm trying to do is write a simple javascript file that will randomly change the color of a text. I'll post where my js and html files are at this point, but really it doesn't matter as its the 100th iteration I've been through.

colors.js

class Color {
  constructor(name, code) {
    this.name = name;
    this.code = code;
  }
}

const allColors = [
  new Color('brightred', '#E74C3C'),
  new Color('soothingpurple', '#9B59B6'),
  new Color('skyblue', '#5DADE2'),
  new Color('leafygreen', '#48C9B0'),
  new Color('sunkissedyellow', '#F4D03F'),
  new Color('groovygray', '#D7DBDD'),
];

export function getRandomColor() {
  return allColors[Math.floor(Math.random() * allColors.length)];
}
export function changeColor() {
  var p = document.querySelector("p");

  p.style.color = "getRandomColor(code)";
}
export allColors = allColors;

At first I was trying to do the changeColor function scripting in the html file, but something had led me to putting it in the javascript file.

index.html

<html>
<head>
  <title>Color changer!</title>
</head>
<body>

<h2>External JavaScript</h2>

<button onclick="changeColor()">Change Random Font Color</button>
<p>Randonmly change the color of this font!</p>
<script src = "colors.js">

</body>

<script src = "colors.js"></script>

</html>

I've gone through literally a couple hundred different versions of this html file. From the super complicated, where I was handling the onclick event on it, to the super simple like I have now.. and I just can't figure it out.

Anyway, if anyone could help me with this I'd appreciate it. I'd really like to keep it as similar to the setup it has now (for me to understand how it would work, even though I'm sure there are easier ways to go about it). Thank you ahead of time.

Tahmid Ali
  • 805
  • 9
  • 29
  • Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`) and read any errors. You’re missing `type="module"`. Please [validate your HTML](//html5.validator.nu/). – Sebastian Simon Jul 19 '21 at 02:59
  • `"getRandomColor(code)"` isn’t a color. `getRandomColor().code` is a color. – Sebastian Simon Jul 19 '21 at 03:00
  • 1
    I wouldn't even bother with creating a class. You just use an object or Map to map the colours to the hex codes. – Paul Rooney Jul 19 '21 at 03:06

1 Answers1

2

Try with

p.style.color = getRandomColor().code;

without quotation marks, as you want the return value of the function, not the name of the function.

AlexSp3
  • 2,201
  • 2
  • 7
  • 24