Each div in prevAlll() will have its own unique CSS background

In continuation of my initial query, which has now been resolved, you can find the original question here.

JS:

$(function() {
 var scaletext = {
  1: 'SA',
  2: 'A',
  3: 'N',
  4: 'Da',
  5: 'SDa'
}
$('.scale').hover(function() {
  var $this = $(this);
  $this.prevAll('.scale').addBack().css('background-color', 'yellow');
   $this.siblings('.scale-text').html(scaletext[$this.data('scale')]);
}, function() {
    var $this = $(this);
    $this.prevAll('.scale').addBack().each(function(){
        $(this).css('background-color', getRandomColor());
    });
    $this.siblings('.scale-text').html("No Rating");
});
});

HTML

<table>
 <thead>
<tr>
  <td>Overall</td>
  <td></td>
  <td></td>
</tr>
</thead>
<tbody>
  <tr>
    <td>Question 1</td>
    <td width="300px">
    <div class="scale-text">No Rating</div>
    <div data-scale="1" class="scale scale-1"></div>
    <div data-scale="2" class="scale scale-2"></div>
    <div data-scale="3" class="scale scale-3"></div>
    <div data-scale="4" class="scale scale-4"></div>
    <div data-scale="5" class="scale scale-5"></div>
  </td>
  <td>Comment</td>
</tr>
<!--Repeat above section for subsequent questions-->

Currently, each div changes to yellow on hover. How can I ensure that each div in the scale displays a different color when hovered over?

Answer №1

One approach is to create an array that holds colors for each element and then utilize the .each() method to set the 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;
}
<script src="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>
    <td width="300px">
    <div class="scale-text">No Rating</div>
    <div data-scale="1" class="scale scale-1"></div>
    <div data-scale="2" class="scale scale-2"></div>
    <div data-scale="3" class="scale scale-3"></div>
    <div data-scale="4" class="scale scale-4"></div>
    <div data-scale="5" class="scale scale-5"></div>
  </td>
  <td>Comment</td>
</tr>
<tr>
  <td>Question 1</td>
  <td width="300px">
    <div class="scale-text">No Rating</div>
    <div data-scale="1" class="scale scale-1"></div>
    <div data-scale="2" class="scale scale-2"></div>
    <div data-scale="3" class="scale scale-3"></div>
    <div data-scale="4" class="scale scale-4"></div>
    <div data-scale="5" class="scale scale-5"></div>
  </td>
  <td>Comment</td>

  ...

  <tr>
  <td>Question 1</td>
  <td width="300px">
    <div class="scale-text">No Rating</div>
    <div data-scale="1" class="scale scale-1"></div>
    <div data-scale="2" class="scale scale-2"></div>
    <div data-scale="3" class="scale scale-3"></div>
    <div data-scale="4" class="scale scale-4"></div>
    <div data-scale="5" class="scale scale-5"></div>
  </td>
  <td>Comment</td>
</tr>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to apply filtering to my data source with checkboxes in Angular Material?

Struggling to apply datatable filtering by simply checking checkboxes. Single checkbox works fine, but handling multiple selections becomes a challenge. The lack of clarity in the Angular Material documentation on effective filtering with numerous element ...

acquire the document via ng-change

I need help converting this code to be compatible with angular.js so that I can retrieve the data URL and send it using $http.post <input type="file" id="imgfiles" name="imgfiles" accept="image/jpeg" onchange="readURL(this);"> function readURL(i ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...

What purpose does the div tagged with the class selection_bubble_root serve in Nextjs react?

Just starting out with Nextjs and setting up a new Next.js React project. I used create-next-app to initialize the code base, but then noticed an odd div tag with the class 'selection_bubble_root' right inside the body. Even though its visibility ...

The issue of JQuery $(this) malfunctioning when used within a function parameter

Encountering an issue with the code snippet below: $(".countdown").circularCountdown({ startDate:$(this).attr('data-start'), endDate:$(this).attr('data-end'), timeZone:$(this).attr("timezone") }); On the contrary, the co ...

Tips for swapping out the content within a "li" element

I am dealing with a situation where I have approximately 100 pages, all containing an <ul> tag, but the issue is that I need to enclose each list item within a <span> tag. Below is the code snippet I have tried: <ul style="list-style-type: ...

Guide to changing an image on a canvas with KineticJS

I am currently working on developing a canvas that will display a hotel floor view. I have images stored in a database which I am drawing onto the canvas using x and y coordinates from the database as reference points. However, I want to add touch events t ...

Using Django Sessions for User Authentication in React Applications

Not a coding query, but rather a general one: When using default authentication in Django (session authentication), what does the frontend (in my case it's React) require? For instance, upon logging in on the browser via the front end login button, th ...

Check if the DIV element does not exist in the DOM before using the

I have been working on a large project and what I need is if div 1 does not contain div 2 as a child{ div1.appendChild(div2) } However, I am facing difficulties in solving this issue Here is my code snippet <script> dc = document.createElement( ...

What is the process for designing a button with a circular element connected to its left edge?

I am currently working on creating a unique button design using a combination of HTML and CSS. The button is rectangular on three sides, with a circular section attached to the right side where the buttons border seamlessly wraps around it. Below is an im ...

Error encountered: Invalid symbol detected ('<') while attempting to parse JSON in an Angular application

I am experiencing an issue with my Angular code when trying to submit a form. Upon clicking the submit button, an error saying JSON Parse error: Unrecognized token '<' appears, and empty records are being saved in the database. I have included ...

A way to effectively utilize a variable containing information retrieved from mongoDB is to pass it to another file, enabling access to the stored data within that variable

Is it possible to utilize a variable containing data from mongoDB in a different react component? This would allow us to access the fetched data from mongoDB stored in that variable. Here is the code for the file where data from mongoDB is fetched and sto ...

What advantages does incorporating SSR with dynamic imports bring?

How does a dynamic imported component with ssr: true differ from a normal component import? const DynamicButton = dynamic(() => import('./Button').then((mod) => mod.Button), { ssr: true, }); What are the advantages of one method over the ...

How can I retrieve the identifier in Socket.io?

Is there a way to retrieve the unique Id from the server using socket.io? I attempted using clients[socket.id] = socket; However, I encountered an error stating: connections property is deprecated. use getconnections() method Does anyone have any sugg ...

Utilizing chart.js data source plugin in React application (react2chartjs)

Upon receiving inspiration from a question regarding importing data from Excel and presenting it as charts using ChartJs (Import data from Excel and use in Chart.js), I was able to successfully achieve this goal. However, my attempt to replicate this proce ...

Tips on extracting values from the nested array using react axios

While the renderQuestions section works fine and prints the first question, there is an issue with the renderChoices part. The desired output is to display the choices for the first question as (a.)1970 b.) 1971 c.)1972 d.)1973) but it currently displays ...

Unlock the Power of EmailJS with Vue.js 2 and TypeScript

I couldn't find a similar issue online, so here's my problem. I'm trying to create a form for receiving contact from an app using Vue.js 2 and TypeScript. Here is my code: <form ref="form" class="form-data" @submit.pr ...

Executing a PHP function every second using JS/Ajax: A step-by-step guide

Currently, I am utilizing the Highcharts API from http://www.highcharts.com/demo/dynamic-update to create a dynamic graph that reflects server load on my web panel. I have developed a PHP function called get_server_cpu_usage() which retrieves the current ...

The equivalent to using $("div").toggle() in jQuery in plain JavaScript would be something like togg

I'm currently utilizing jQuery and am interested in converting certain methods to native JavaScript. When using jQuery, the code looks something like this: $("div").toggle() Is there a way to convert this to native JavaScript, perhaps like below? ...

Tips on how to modify database records rather than generating new ones

Currently, my team is developing a web application that utilizes wearables to monitor vital parameters. As part of our integration testing, we are using a Fitbit device. The app itself is built with Angular and JavaScript, while the database is hosted on C ...