Illuminate a group of items when hovering over them

While attempting to change the color of 1 to 5 elements on mouse hover based on the data-rating tag, I am encountering a few issues. The data is retrieved correctly, but there are some problems:

  1. The function is being called 5 times each time there is a hover, instead of just once.
  2. All elements receive the color upon mouse enter, then all 5 colors are removed upon mouse leave.
  3. I believe there must be a more efficient way to achieve this, especially in the loop section. I aim to keep it DRY (Don't Repeat Yourself) here, and the current method definitely does not adhere to that principle.

The HTML code snippet:

<h2>
  <i class="far fa-star" data-rating="1">1</i>
  <i class="far fa-star" data-rating="2">2</i>
  <i class="far fa-star" data-rating="3">3</i>
  <i class="far fa-star" data-rating="4">4</i>
  <i class="far fa-star" data-rating="5">5</i>
</h2>

The jQuery part:

$('[class="far fa-star"]').mouseenter(function() {
  var target = parseInt($(this).data('rating'));

  for (i = 0; i < target; i++) {
    $(this).parent().children(i).css('background-color', 'yellow');
  }
});

$('[class="far fa-star"]').mouseleave(function() {
  var target = parseInt($(this).data('rating'));

  for (i = 4; i > target; i--) {
    $(this).parent().children(i).css('background-color', 'transparent');
  }
});

Check out the fiddle here: fiddle

Answer №1

It seems like there was some confusion with the previous responses, but I believe I understand your request for a highlighting feature in your rating system. Here is an example that demonstrates how to achieve this:

// This code snippet uses event delegation to highlight stars on mouseover
document.querySelector("h2").onmouseover = function(e) {
  // Check if the element is an <i> tag
  if(e.target.nodeName === "I") {
    // Get the current star's rating
    var rating = e.target.getAttribute("data-rating");
    // Change the color of stars based on their position relative to the hovered star
    Array.prototype.forEach.call(this.children, (c, i) => c.style.color = i < rating ? "yellow" : "black");
  }
}

// Reset the color of all stars on mouseleave
document.querySelector("h2").onmouseleave = function() {
  Array.prototype.forEach.call(this.children, c => c.style.color = "black");
}
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<h2>
  <i class="fas fa-star" data-rating="1"></i>
  <i class="fas fa-star" data-rating="2"></i>
  <i class="fas fa-star" data-rating="3"></i>
  <i class="fas fa-star" data-rating="4"></i>
  <i class="fas fa-star" data-rating="5"></i>
</h2>

Answer №2

To add a background color in CSS, simply use the :hover pseudo-class


.yourclass:hover{
    background-color: lightblue;
}

Answer №3

Applying Background Color Using :hover Pseudo Class in CSS


.yourclass:hover{

background-color: blue;

}

Alternatively, You Can Implement an Event Listener

Answer №4

After reviewing your code, I believe CSS is the solution for achieving this. Make sure to take a look at this related question for additional guidance.

Answer №5

Here is a code snippet that can help you achieve the desired effect:

$('[class="far fa-star"]').mouseenter(function () {
var rating = parseInt($(this).data('rating'));

for (i = 0; i < rating; i++) {
    $(this).parent().children().eq(i).css('background-color', 'yellow');
}
});
$('[class="far fa-star"]').mouseleave(function () {
var rating = parseInt($(this).data('rating'));

for (i = 0; i < rating; i++) {
    $(this).parent().children().eq(i).css('background-color', 'transparent');
}
});

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

When attempting to access Firestore on a non-local server without using a virtual machine on AWS, the following error occurs: { Error: Module 'grpc' not found

My code runs successfully locally and connects to the same firestore. However, when I push it to my release server and hit the endpoint, I encounter this error: { Error: Cannot find module 'grpc' at Function.Module._resolveFilename (module.j ...

Can you include both a routerLink and a click event on the same anchor tag?

I am facing an issue with my li elements. When a user clicks on them, it should open a more detailed view in another component. However, I noticed that it takes TWO clicks to show the data I want to display. The first click opens the component with an em ...

Tips for incorporating captions into a slideshow

I've been experimenting with different methods to include captions in my slideshow, but haven't had much success. I simply want to add a div at the bottom of each image. Do I need to modify my script or should I consider adding something else? H ...

All web browsers are supported by the HTML time input type for time formatting

Hello there, I'm currently dealing with an issue in my Angular / JHipster project. The problem lies with the input Forms, specifically the one with Type="TIME". While it displays correctly on my browser as (12:24), other browsers show it differently ...

Enhancing Communication Between JavaScript and PHP

Positioned within my form is an input field where users can enter their postcode. The shipping cost for their order will be determined based on this postcode, utilizing PHP to assign different costs depending on the zone. After the user enters their postc ...

Is there a way to adjust a simple program using Discord.js where the setTimeout within a for-loop can print values sequentially instead of simultaneously?

Here is the code I'm using: for (let i = 0; i <= 5; i++) { delay(i); } function delay(i) { setTimeout(() => console.log(`${i} is the number`), 2000); } The output I'm currently getting after 2 seconds is: 0 is the number 1 is the ...

Challenges encountered when sending a variable from jQuery to PHP

I came across the following code snippet: <?php $id = $_GET['id']; ?> <html> <head> <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> </head> <body> <script& ...

Establishing connections in neo4j with the neo4j-nodejs API

I encountered an error while creating a relationship between two nodes that were generated within the code. Can someone advise me on the correct arguments for the function below and its proper formatting? node1.createRelationshipTo(node2, "some", {age:" ...

How can you animate a MUI v4 Grid element using CSS transitions?

I was exploring the potential of using breakpoints in the MUI v4 component to control the visibility of items in my Grid System. How can I create a smooth CSS transition for b, transitioning from 0px to a defined breakpoint size of 3 for xl? Using % works ...

What is the correct way to assign a $scope variable after a successful ajax call?

Currently, I am working with Symfony and AngularJs 1.6.8 along with Symfony 3.4. Below is the configuration setup that I have: base.html.twig <html lang="en" data-ng-app="CeocApp" ng-controller="CeocController"> //css for the app <link id="ng ...

Identifying an Incorrect Function Call in a TypeScript Function from a JavaScript File [TypeScript, Vue.js, JavaScript]

I have a vue2 application and I am looking to incorporate TypeScript into some service files without modifying the existing js/vue files. To enable TypeScript support, I utilized vue-cli which allowed me to successfully add a myService.ts file containing ...

The outcome of the AJAX RSS Reader remains unpredictable

Utilizing the AJAX RSS Reader (visit this link) for extracting RSS data from my URL: http://vtv.vn/trong-nuoc.rss In my php file (readRSS.php): <?php $url = ("http://vtv.vn/trong-nuoc.rss"); $xmlDoc = new DOMDocument(); $xmlDoc->load($url); $ ...

Create a dynamic table using an array in jQuery

Currently, my goal is to generate a table using an array with the following format: [ { header: 'ID', values: [1, 2] }, { header: 'First Name', values: ['John', 'Jayne'] }, { header: &ap ...

Is it possible to transmit identical data from a form to two distinct actions in Symfony5?

UNIQUE LOGIN TEMPLATE {% extends 'base.html.twig' %} {% block title %}Welcome to the Login Page!{% endblock %} {% block body %} {% if error %} <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div& ...

Implementing Facebook conversion tracking when there is no distinct 'Thank you' page can be done by utilizing the onclick event

Currently working on incorporating Facebook conversion tracking into a Facebook Tab. To see the page, visit this link. The issue I'm facing is that a separate page does not load after the form has been submitted. Is there a way to execute a section of ...

Utilizing Ajax for JSON data transmission and handling with Spring MVC Controller

I am working on an ajax json POST method that looks like this. $(function () { $('#formId').submit(function (event) { event.preventDefault(); // prevents the form from being submitted var u ...

problem with selection of date and month in dropdown list with jquery

Recently, I've been dabbling in jQuery and decided to create two list boxes using it. One box contains dates while the other contains months. It's quite handy since I need them in different sections of my HTML page. However, when attempting to en ...

Automatically populate a dropdown list based on the selection made in another dropdown menu

I'm populating a second textbox based on the input of the first textbox in auto.jsp. Now, I want to automatically populate a combo box as well. How can I achieve this? Specifically, I want to autofill the second combo box based on the selection made i ...

Learn how to properly display the state array within a React component. Even though the array is present in the state, you may encounter issues where it

I am facing an issue while trying to display data from firestore in my React component. I have updated the global state array with the firestore data and it is being updated, but when I try to render that array, it shows as undefined. Initially, I attempt ...

Managing an undetermined quantity of elements from a form in PHP

Currently developing an inventory page for my job. I've crafted a page that will iterate through my database and showcase all the items stored within. include 'auth.php'; //authentication required for login change $sql="SELECT * FROM `inven ...