Sunday, 5 March 2023

jQuery Toggling Background Color to Table Row on Click

In this jQuery code for Toggling Background Color to Table Row on Click, we first use jQuery to select all tr elements and add a click event listener to them. When a tr is clicked, we use the toggleClass() method to toggle the highlight class on that tr. The highlight class is defined in the CSS code and sets the background color to yellow.

$(document).ready() function is used to ensure that the code is executed only after the page has finished loading.

 <!DOCTYPE html>
<html>
<head>
  <title>jQuery Toggling Background Color to Table Row on Click</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
    }
    th, td {
      padding: 8px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }
    th {
      background-color: #f2f2f2;
    }
    .highlight {
      background-color: yellow;
    }
  </style>
</head>
<body>
  <table>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Department</th>
    </tr>
    <tr>
      <td>1</td>
      <td>John Doe</td>
      <td>Marketing</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Jane Smith</td>
      <td>IT</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Bob Johnson</td>
      <td>Finance</td>
    </tr>
  </table>
 
  <script>
    $(document).ready(function() {
      $('tr').click(function() {
        $(this).toggleClass('highlight');
      });
    });
  </script>
</body>
</html>

0 comments:

Post a Comment

Please do not enter any spam link in the message box.