Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Getting a Handle on the DOM Selecting by Id

Vic Mercier
Vic Mercier
3,276 Points

random color each time detect click

It's work here but not in my workspace?

js/app.js
const my = document.getElementById("lol");
my.style.color = "red";
index.html
<!DOCTYPE html>
<h1 id = "myNAME">VICTOR</h1>
<button id = "myBUTTON">RANDOM COLOR</button>
<script>
const name = document.getElementById("myNAME");
const myButton = document.getElementById("myBUTTON");
myButton.addEventListener("click",()=>{
  const randomColor = Math.floor(Math.random()*1000000);
randomColor.toString();
  name.style.color= "#"+randomColor;
});


</script>

1 Answer

the index.html file works for me in both workspaces and locally. However you are missing some standard tags like the opening and closing html tags inside index.html, and I am unsure what the file app.js has to do with the index.html file because you do not have a link to app.js anywhere.

Also, limiting the random color generator to colors between #000000 and #999999 are going to result in some very dark colors, to the point of not being able to determine if your name has in fact changed color. I would suggest an alternate approach to create a random color generator like so:

function color(){
  const letters = "0123456789abcedf";
  let color = "#";
  for(let i = 0; i < 6; i++){
    color += letters[Math.floor(Math.random()*16)]
  }
  return color;
}

this will give you all possible color combinations because it includes the hex color letters as well.