Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

80
Vistas
change background with every click

My problem is that when I click on the TR tag, it shows a color, and when I click again, the background color goes, and so far so good. But when I click again, the color does not show where is the problem??

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
$('.tr').click(function() {
  $('.tr').css("background-color", "");
  $(this).css({
    "background-color": getRandomColor()
  });
  $(this).click(function() {
    $(this).css("background-color", "initial");
  });
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link rel="stylesheet" href="css/style.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
  <table class="table table-bordered table-hover w-99">
    <tbody>
      <tr class="tr">
        <td>654</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
  </table>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</body>

</html>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Nesting click events is generally a bad idea as they often don't work as expected.

In this case,

  $(this).click(function() {
    $(this).css("background-color", "initial");
  });

isn't replacing the initial $(".tr").click so they both run every time after the 1st click.

One option would be to use .off("click") and add the other handler, but it's a bit messy.

Normally, I'd suggest using toggleClass to set your background, but as it's a random colour, that's not an option.

However, you can still add a class (or use .data(.., ..)) to indicate if it needs resetting:

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

$('.tr').click(function() {
  // clear rows
  $('.tr')
  .css("background-color", "")
    .not(this)
    .removeClass("random");

  if (!$(this).hasClass("random")) {
    $(this).css({
        "background-color": getRandomColor()
      })
      .addClass("random");

  } else {
    $('.tr').removeClass("random");
    // no need to reset $(this).background-color as reset above

  }
});
.random {
  /* nothing here */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<table class="table table-bordered table-hover w-99">
  <tbody>
    <tr class="tr">
      <td>987</td>
    </tr>
    <tr class="tr">
      <td>654</td>
    </tr>
    <tr class="tr">
      <td>321</td>
    </tr>
  </tbody>
</table>

about 4 years ago · Juan Pablo Isaza Denunciar

0

just removed a little bit of your code and added the css user-select: none; to prevent text-selection after multiple clicks.

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
$('.tr').click(function() {
   console.log(getRandomColor())
  $('.tr').css("background-color", getRandomColor());
})
td {
 user-select: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link rel="stylesheet" href="css/style.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
  <table class="table table-bordered table-hover w-99">
    <tbody>
      <tr class="tr">
        <td>654</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
  </table>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</body>

</html>

hint: be aware to switch the font color to a white one, when the backgroud is too dark. Maybe there is a jQuery method to detect the contrast.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use a hasColor as a boolean to tracking status.

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

$('.tr').click(function() {
  var hasColor = $(this).attr('hasColor');
  if (!hasColor) {
    var hasColor = $(this).attr('hasColor', true);
    $(this).css({
      "background-color": getRandomColor()
    });
  } else {
    var hasColor = $(this).attr('hasColor', '');
    $(this).css("background-color", "");
  }
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link rel="stylesheet" href="css/style.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
  <table class="table table-bordered table-hover w-99">
    <tbody>
      <tr class="tr">
        <td>654</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr class="tr">
        <td>654</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
  </table>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda