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

124
Views
Click change color

I am working on a website and I want that when the user clicks on a specific card, it turns blue. I have searched and found some things online, but it is not working for me and I don't know why; here is the code:

<div class="card" onclick="myFunction()">
  <p class="number-card">1</p>
</div>

<script>
  function myFunction() {
    document.getElementById("card").style.backgroundcolor = "blue";
  }
</script>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  • You're missing an ID - anyways, use Classes instead with document.querySelectorAll(".card") MDN querySelectorAll
  • Should be backgroundColor with capital C
  • Use Element.addEventListener() instead of inline JS on* attribute handlers. JS and styles should always be in their respective tags or files, not disseminated around a HTML file.
  • Read about Event.currentTarget

<div class="card">
  <p class="number-card">1</p>
</div>

<div class="card">
  <p class="number-card">2</p>
</div>

<script>
  const changeBgColor = (ev) => {
    ev.currentTarget.style.backgroundColor = "blue";
  };
  const EL_cards = document.querySelectorAll(".card");
  EL_cards.forEach(EL => EL.addEventListener("click", changeBgColor));
</script>

Alternatively, using a regular function (where addEventListener binds by default this to the Event.currentTarget Element):

function changeBgColor() {
  this.style.backgroundColor = "blue";
}
about 4 years ago · Juan Pablo Isaza Report

0

You only have the class set to card but you're trying to getElementById, you should give the div an id that's unique and change the function.

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!