Creating a rating system with half-star increments in JavaScript for a five-star scale

Trying to figure out how to create a JavaScript function that can adjust the star rating of an element based on a score using jQuery's addClass and removeClass. I previously had a function for displaying whole stars, but now I am struggling with implementing a system for half-star ratings. Here is my previous code:

function() {
    $(this).prevAll().andSelf().addClass('active');  
    $(this).nextAll().removeClass('active');
}

Does anyone have any advice on how to modify this function for a half-star system? Below is the current code I am working with:

function populateStars(stars, score) {
    // The "stars" parameter refers to the container <ul> with individual <li> elements for each star.
    // This function should dynamically update the star display based on the given score (ranging from 1 to 5).
}

Here is an example of the HTML structure that "stars" variable points to:

<ul class="big-stars">
    <li class="star-1 full">1</li>
    <li class="star-2 full">2</li>
    <li class="star-3 half">3</li>
    <li class="star-4">4</li>
    <li class="star-5">5</li>
</ul>

And here is the CSS responsible for styling the stars as full, empty, or half-full:

.big-stars li {
    text-indent: -9999px;
    width: 49px;
    height: 46px;
    background: url('../images/big_star_empty.png');
    }
.big-stars .full {
    background: url('../images/big_star_full.png'); 
    }
.big-stars .half {
    background: url('../images/big_star_half.png'); 
    }

Answer №1

function displayStars (stars, rating) {
    var wholeStars = Math.floor(rating);
    var hasHalfStar = (wholeStars < rating);

    for (var starNum = 1; starNum <= wholeStars; starNum++) {
        $('li.star-' + starNum, stars).addClass('full');
    }

    if (hasHalfStar) {
        $('.star-' + starNum, stars).addClass('half');
    }
}

displayStars($('.big-stars'), 3.5)

This code can be simplified by moving variable declarations closer to their usage.

Edit: Check out this JSFiddle demo :) http://jsfiddle.net/G8kwb/
Edit 2: Updated JSFiddle link with rounding to the nearest half number: http://jsfiddle.net/G8kwb/8/

Answer №2

Consider this alternative approach, utilizing jQuery's lt and eq selectors:

function fillStars (stars, rating)
{
   //round to the nearest half
   rating = Math.round(rating * 2) / 2;

   var ratingParts = rating.toString().split('.');
   $(stars + ' li:lt('+ ratingParts[0]+')').addClass('full');

   if(ratingParts[1])
   {
       $(stars + ' li:eq('+ ratingParts[0] +')').addClass('half');
   }
}

fillStars('.big-stars', 3.5);

Ensure you provide the parent class as input rather than the specific object when calling the function, offering an intriguing option for customization.

Update: check out this revised fiddle with rounding included: jsFiddle, credits to Joe for the original version!

In addition, I discovered the rounding technique in a compelling related inquiry - Transforming a number into star rating display.

Answer №3

If you're in need of a solution, here's what I have devised. It might benefit someone (using fontawesome to represent the stars, though styled elements can be used as well):

function determineStarRating(rating){

    // Round down to calculate full stars:
    var fullStars = Math.floor(rating);
    // Check if the whole number is less than the rating.
    // If it is less than the rating, then a half star is required:
    var halfStars = (fullStars < rating);

    var result = "";
    //Iterate through five stars:
    for(let i=1; i<=5; i++){
      //For stars less than or equal to total stars, show a solid star:
      if(i <= fullStars){
        result+= "</i><i class='fas fa-star' style='color:#fbcc05'></i>";

      //If iteration is after a full star and a half star is necessary, display a half star:
      } else if( i == fullStars+1 && halfStars == true ){
        result+= "<i class='fas fa-star-half-alt' style='color:#fbcc05'></i>";

      //Otherwise, show a gray empty star:
      } else {
        result+= "<i class='far fa-star' style='color:#bfbfbf'></i>";
      }
    }
    return result;
  }

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

Laravel 5.2 is designed to exclusively extract numerical values from AJAX post requests

When using AJAX to submit my form, I encountered an issue where only the numeric values were being passed through. Even though all variables appeared populated before submitting the form, only the numeric ones made it to the controller. AJAX: function ap ...

What is the best way to reveal the menu options by tapping on the top left icon?

Seeking guidance on how to activate the menu by clicking the top left corner icon. A sample code setup is available in Codepen through this link: https://codepen.io/RSH87/pen/rmgYbo. I require assistance with incorporating the JavaScript file into my React ...

Is there an issue with sending standard form data to PHP using jQuery if not all index values are being received

Having issues submitting the form to PHP as not all data is being passed properly? Below is the jQuery code used to initialize the post: var fieldsdata = $('form').serialize() $.post( "index.php", fieldsdata, function(data){ console.log( d ...

NodeJS process that combines both client and server functionality

Attempting to develop a test echo server with both client and server in the same node process. When the code is split into two files (server and client), it functions correctly, but when combined into one file, it fails. How can I make it work within a sin ...

What is the best method for inserting a specific value into a tuple that exists within another tuple within Python using Django?

My dictionary for Categories consists of tuples within a tuple, but I am looking to extract only the literals - the category names. from django.db import models CATEGORIES = ( ('a', 'Clothing'), ('b&ap ...

Tips for filling the offset space with a column

Having a bit of trouble phrasing my question, but here's the issue I'm facing: Currently, I need to develop two different views, the first being the mobile view However, I'm experiencing some difficulties with the second view, which can be ...

What is the best way to link my JSON object to specific properties of my data object in vue.js?

I am currently using Vue.js for my frontend development and I have a JSON object that I need to map to set certain properties in my data(). I have confirmed that the server connection is working and that the JSON object is received properly. In my comput ...

Optimizing TypeScript/JavaScript for both browser and Node environments through efficient tree-shaking

I am currently tackling a TypeScript project that includes multiple modules shared between a browser client and a Node-based server. Our goal is to bundle and tree-shake these modules using webpack/rollup for the browser, but this requires configuring the ...

The Register Page is failing to load

I'm currently tackling a validation form project with NodeJS. However, I'm encountering an issue where register.ejs is refusing to render. Despite my attempts to tweak the paths and navigate through different folders, the problem persists. As a n ...

Leveraging JavaScript Variables with Android Development

How can I extract a JavaScript variable from a website and incorporate it into my code? I followed the steps in this guide to display the string in an alert message, but now I'm unsure how to use it outside of the alert. Any advice would be appreciate ...

avoiding retrieval of historical data in mongodb atlas using a Node.js application

It's been 10 days since I last used mongodb atlas. When I try to connect my node application after this time, it returns a blank array in the find Query from Node application. However, when I insert new data into mongodb atlas using the Node applicati ...

Troubleshooting Parallax Logic in NextJS

import Head from 'next/head' import styles from '../styles/Home.module.css' import Image from 'next/image' import React, { useRef ,useEffect, useState } from 'react'; export default function Home() { let ref = use ...

Verify if there are DOM elements located within a DIV container, execute the functions associated with those elements sequentially

I am in the process of creating a game using HTML, CSS, and JavaScript. My focus right now is on manipulating DOM elements without relying on the canvas tag. The goal is to develop a pseudo graphical programming language, similar to the environment provide ...

attaching the model to chosen values rather than defining the chosen item

This is the coding I am currently using which is functioning correctly: <div class="col-md-12"> <div class="button-group"> <button type="button" class="btn btn-default btn-block btn-sm dropdown-toggle" data-toggle="dropdown"> ...

Vue warning: Issue encountered in created hook - Attempting to access property 'get' of an undefined variable is causing a TypeError

I encountered an error while using axios: [Vue warn]: Error in created hook: "TypeError: Cannot read property 'get' of undefined" export default { methods: { loadUsers(){ axios.get("api/user").then(data => ...

How can Bootstrap Modal Popup utilize Jquery Post validation effectively?

Trying to set up a popup and form with validation, but encountering an issue where the modal is not appearing. <div id="thanks" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="moda ...

Tips for incorporating JSON data into an HTML table

https://i.sstatic.net/WEdge.jpgIn an attempt to showcase JSON data in an HTML table, I want the schoolClassName value to be displayed as a header (th) and the first names of students belonging to that specific schoolClass to appear in a column beneath the ...

Strategies for sorting through numerous characteristics of a hierarchical array that may stretch across multiple levels of the tree

In order to simplify the process, I am looking for a way to filter multiple properties of a parent-child array that may have multiple levels. This is specifically for an Open Source datagrid library that is utilized by hundreds of users. The array consist ...

The Angularfire library encountered an issue when trying to access the 'push' property of a null object

I am currently in the process of creating a new object in the database for an assessment. Right now, I have hardcoded it to test its functionality, but ultimately, it will be dynamic based on user input from the view. However, I am encountering an error th ...

Javascript is unable to access the occupied value. Error: Unable to read property 'weight' of undefined

I encountered a strange issue that I wasn't expecting. The snippet of code below represents a simple function. However, the problem arises when I try to access 'truckArray[0].weight' and receive an error stating TypeError: Cannot read prop ...