Skip to content Skip to sidebar Skip to footer

Different Css Background For Each Div In Prevalll()

Following on from my original (now answered) question here: Dont update multiple divs on hover events JS: $(function() { var scaletext = { 1: 'SA', 2: 'A', 3: 'N', 4: 'Da'

Solution 1:

Try creating an array containing colors to be applied , using .each() to set background of each .scale element

$(function() {
 var scaletext = {
  1: 'SA',
  2: 'A',
  3: 'N',
  4: 'Da',
  5: 'SDa'
};
  
var colors = ["red", "darkorange", "orange", "yellow", "green"];
  
$('.scale').hover(function() {
  var $this = $(this);
  $this.prevAll('.scale').addBack().each(function(i) {
    $(this).css("background", colors[i])
  })
  $this.siblings('.scale-text').html(scaletext[$this.data('scale')]);
}, function() {
   var $this = $(this);
   $this.prevAll('.scale').addBack().css('background-color', '');
   $this.siblings('.scale-text').html("No Rating");
 });
});
td > div.scale {
  padding: 5px;
  background-color: lightgrey;
  display: inline-block;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><table><thead><tr><td>Overall</td><td></td><td></td></tr></thead><tbody><tr><td>Question 1</td><tdwidth="300px"><divclass="scale-text">No Rating</div><divdata-scale="1"class="scale scale-1"></div><divdata-scale="2"class="scale scale-2"></div><divdata-scale="3"class="scale scale-3"></div><divdata-scale="4"class="scale scale-4"></div><divdata-scale="5"class="scale scale-5"></div></td><td>Comment</td></tr><tr><td>Question 1</td><tdwidth="300px"><divclass="scale-text">No Rating</div><divdata-scale="1"class="scale scale-1"></div><divdata-scale="2"class="scale scale-2"></div><divdata-scale="3"class="scale scale-3"></div><divdata-scale="4"class="scale scale-4"></div><divdata-scale="5"class="scale scale-5"></div></td><td>Comment</td></tr><tr><td>Question 1</td><tdwidth="300px"><divclass="scale-text">No Rating</div><divdata-scale="1"class="scale scale-1"></div><divdata-scale="2"class="scale scale-2"></div><divdata-scale="3"class="scale scale-3"></div><divdata-scale="4"class="scale scale-4"></div><divdata-scale="5"class="scale scale-5"></div></td><td>Comment</td></tr><tr><td>Question 1</td><tdwidth="300px"><divclass="scale-text">No Rating</div><divdata-scale="1"class="scale scale-1"></div><divdata-scale="2"class="scale scale-2"></div><divdata-scale="3"class="scale scale-3"></div><divdata-scale="4"class="scale scale-4"></div><divdata-scale="5"class="scale scale-5"></div></td><td>Comment</td></tr>

Post a Comment for "Different Css Background For Each Div In Prevalll()"