Heisenberg
Heisenberg

Reputation: 5299

How to change class to currently hovered cells in html tables

When I tried to change class with hovering, I can see class change from1 to hovering cells

But I would like to change class from1 to currently hovered cells

if mouse move 1 to 10 to 2 ,then currently hovered cells=2 therefore only 1and2 will be changed.

But now in such case,class of 1to10is changed.

Are there any way to realize it?

Thanks

$("td").hover(function() {
    const id = Number($(this).attr('id'));
    
    for(var j = 1;j <= id; j++){
      $("#"+j).addClass("aqua");
    }
  });
.aqua{
  background-color: aqua;
}


td {
  padding: 10px;
  transition-duration: 0.4s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td id="1">1</td>
  <td id="2">2</td>
  <td id="3">3</td>
  <td id="4">4</td>
   </tr>
 <tr>
  <td id="5">5</td>
  <td id="6">6</td>
  <td id="7">7</td>
  <td id="8">8</td>
    </tr>
  <tr>
  <td id="9">9</td>
  <td id="10">10</td>
  <td id="11">11</td>
  <td id="12">12</td>
  </tr>
</table>

Upvotes: 2

Views: 60

Answers (1)

Batu.Khan
Batu.Khan

Reputation: 3065

First you need to remove classes. Then add again.

$("td").hover(function() {
    const id = Number($(this).attr('id'));
    $("table td").removeClass("aqua");
    for(var j = 1;j <= id; j++){
      $("#"+j).addClass("aqua");
    }
  });
.aqua{
  background-color: aqua;
}


td {
  padding: 10px;
  transition-duration: 0.4s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td id="1">1</td>
  <td id="2">2</td>
  <td id="3">3</td>
  <td id="4">4</td>
   </tr>
 <tr>
  <td id="5">5</td>
  <td id="6">6</td>
  <td id="7">7</td>
  <td id="8">8</td>
    </tr>
  <tr>
  <td id="9">9</td>
  <td id="10">10</td>
  <td id="11">11</td>
  <td id="12">12</td>
  </tr>
</table>

Upvotes: 2

Related Questions