Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
JS RandomColor Change on hover

I want to change the color randomly on hovering <a class="c-link" but it doesn't work and I wonder what I am doing wrong here.

<!doctype html>
<html>

<script>
  window.onload = function() {
    function randomColor() {
      let color = [];
      for (let i = 0; i < 3; i++) {
        color.push(Math.floor(Math.random() * 256));
      }
      return 'rgb(' + color.join(', ') + ')';
    }

    document.querySelector('c-link').addEventListener("mouseover", function() {
      document.a.style.fontcolor = randomColor();
    });
  }
</script>
</head>

<body>

  <div class="c-text__layer">
    <div class="c-text">Lorem ipsum dolor sit amet consetetur,<br> sadipscing elitr,
      <a class="c-link" href="https://stackoverflow.com/"> sit amet dolor</a></div>
  </div>
</body>

</html>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to specify the class with a . within the query selector. Therefore querySelector('.c-link').

You cannot just call document.a because a is not a property or method of the document object.

Also, there is style.color and style.font but not fontcolor.

Instead use another selector: querySelector('a') to select all the anchors in the document. This will affect every link though. If you only want it to work for one or a few elements you could use the data-attribute, an id or even other CSS classes instead of targeting a in the querySelector.

You can also read a bit on MDN to learn more about JS and the web.

<!doctype html>
<html>
<script>
  window.onload = function() {
    function randomColor() {
      let color = [];
      for (let i = 0; i < 3; i++) {
        color.push(Math.floor(Math.random() * 256));
      }
      return 'rgb(' + color.join(', ') + ')';
    }

    document.querySelector('.c-link').addEventListener("mouseover", function() {
      document.querySelector('a').style.color = randomColor();
    });
  }
</script>
</head>

<body>

  <div class="c-text__layer">
    <div class="c-text">Lorem ipsum dolor sit amet consetetur,<br> sadipscing elitr,
      <a class="c-link" href="https://stackoverflow.com/"> sit amet dolor</a></div>
  </div>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!