Is it possible to generate a star rating system from an image using a decimal value?

Recently, I have been eager to convert a number into a star rating and stumbled upon this helpful post here: . The post perfectly explains what I am looking to achieve. Despite following the instructions provided, I am facing difficulties getting it to function properly in my local environment. Therefore, I am reaching out for assistance. Below is my attempt:

$.fn.stars = function() {
    return $(this).each(function() {
        // Extract the value
        var val = parseFloat($(this).html());
        // Ensure the value falls within 0 - 5 range, multiply to determine width
        var size = Math.max(0, (Math.min(5, val))) * 16;
        // Create stars container
        var $span = $('<span />').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}

$(function() {
    console.log("Calling stars()");
    $('.results-contents span.stars').stars();
});
.results {
    font-size: 0;
    padding-bottom: 16px;
}

.results-content {
    font-size: 13px;
    display: inline-block;
    margin-left: 20px;
    vertical-align: top;
}

.results .results-content span.stars span.stars span {
    background: url('/resources/graphics/stars-icons.png') 0 -36px repeat-x;
    width: 175px;
    height: 80px;
}

.results .results-content span.stars {
    max-width: 80px;
    background-position: 0 0;
}
<script type="text/template" id="results-template">
  <div class="results">
    <div class="results-content">
      <span class="stars">4.0</span> 
    </div>
  </div>
</script>

Star Image:

https://i.sstatic.net/rwkqF.png

My intention was to display empty stars initially, then overlay orange stars based on the rating to represent full and half-star ratings. However, all I see is a number displayed. Although my console.log appears to be functioning, the rendering of the image and calculation of star ratings seem to be problematic. Any assistance would be highly appreciated. Thank you!

Answer №1

You encountered several issues ranging from incorrect CSS styles to an erroneous selector. The rendering may not be perfect, but it is functional.

$.fn.stars = function() { 
  return this.each(function() {
    // Obtain the value
    var val = parseFloat($(this).html()); 
    // Ensure that the value falls within the range of 0-5, then calculate width
    var size = Math.max(0, (Math.min(5, val))) * 36.5; 
    // Create a container for the stars
    var $span = $('<span> </span>').width(size); 
    // Replace the numerical value with stars
    $(this).empty().append($span);
  });
}

$(function() {
  console.log("Calling stars()");
  $('.results-content span.stars').stars();
});
.results {
  font-size: 0;
  padding-bottom: 16px;
}
.results-content {
  font-size: 13px;
  display: inline-block;
  margin-left: 20px;
  vertical-align: top;
  background: url('https://i.sstatic.net/rwkqF.png') 0 0 repeat-x;
  width: 185px;
  height: 35px;
}
.results .results-content span.stars span {
  background: url('https://i.sstatic.net/rwkqF.png') 0 -36px repeat-x;
  display: inline-block;
  height: 35px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results">
  <div class="results-content">
    <span class="stars">0.0</span> 
  </div>
</div>
... Additional code snippets here ...
<div class="results">
  <div class="results-content">
    <span class="stars">5.0</span> 
  </div>
</div>

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

Providing structured Express app to deliver HTML and JavaScript content

Currently, I am working with Express and facing a seemingly simple challenge. Here is the structure of my directories: |-config |---config.js |---routes.js |-server.js |-scripts |---controllers |------controllers.js |---directive ...

angular select radio group index in mat

Within a loop, I have a radio button in a mat radio group where the button and card should change color based on the selected index. However, as shown in the screenshot, the radio button is selected but not displaying in white. https://i.sstatic.net/epcPy ...

Encountered a hard navigation error in NextJs when trying to navigate to the same URL while passing a query string

Currently, I am using NextJs version 13.0.2 and ReactJs version 18.2.0. My goal is to include a query string in the URL; however, I encounter the following error: Error: Invariant: attempted to hard navigate to the same URL /@workamirdanesh?w=true http://l ...

Stop a looping animation keyframe in CSS and make it animate back to the beginning

I am facing an issue with a looping animation that rotates a square. Whenever I remove the class responsible for the animation, the square immediately returns to its initial position. My objective is to animate the square back to the starting position upo ...

Retrieving data from the JSON encoded server response using Ajax to access an array

Upon making a post request with ajax using JSON encoding, I encountered a response that came in the form of an array (see code snippet below). requestparser.php: $array = array("phweb" => "yes", "phemail" => "yeeess"); echo json_encode($array); Th ...

AngularJS templateUrl versus template: what's the difference?

When it comes to routing, I believe that templateUrl is the preferred choice over template. However, when dealing with directives, the decision between using templateUrl or template can be a bit more nuanced. Some developers opt to include chunks of HTML i ...

Struggling with grasping the concept of promises in AngularJS

I encountered a challenge while working with AngularJS & REST. My data service was not returning data in time for my model to use, despite implementing a promise. I would greatly appreciate any assistance from those more knowledgeable on this matter. In ...

What is the best way to transfer information from an API to a state hook?

Encountering a recurring issue that requires some guidance. I am working on an API call and need to display the results in another component within the form's child elements. I've managed to create a component that can map state to JSX, but I&apo ...

What might be the reason for jQuery not functioning in Internet Explorer 11?

Working on developing a slideout menu for my website using jQuery. It functions perfectly in Chrome, but encountering issues in Internet Explorer (IE11). Extensive search hasn't provided a solution yet. Seeking assistance and any help would be highly ...

Ui-router experiencing issues with nested view loading due to changes in URL

I have been developing an application and previously used ui-router successfully with Ionic. The issue I am facing now is that although the URL changes correctly as expected, nothing happens afterwards. I am certain that the template is being found because ...

ParcelJS takes a unique approach by not bundling imported JavaScript libraries

My NodeJS app, which is a Cloudflare Worker, seems to be having trouble with bundling the 'ping-monitor' dependency. In my main typescript file (index.ts), I import the handler module and the first line reads: const Monitor = import('ping-m ...

Exploring the concept of parent-child coupling in React and its connection to context

While delving into React's documentation on Context > Parent-child coupling, I found myself struggling to grasp the concept of parent-child coupling. One particular line stood out: By passing down the relevant info in the Menu component, each Me ...

Getting the user's language in PhoneGap can be done in a variety of ways

I attempted to retrieve the language value of the device using the globalization plugin. I followed all installation procedures, read through the documentation, and searched for answers on this platform, but unfortunately, none of them provided the solutio ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

Three fixed position divs arranged horizontally side by side

I am attempting to organize 3 divs in a row using Flex. ISSUE 1: The div that is centered is set with position: fixed. However, the two other divs on each side do not stay aligned with the centered fixed div when scrolling. If I change the centered div to ...

Dynamically showcasing content in an HTML table

Having trouble with this code snippet. It's supposed to iterate through array objects and display them in an HTML table. The third row should have buttons, but nothing is showing up. Can you spot the issue? Here's the HTML code: <html> & ...

Encountered an error with a JSON object in node and express: Unexpected colon token

I'm currently in the process of developing a small web service using Node.js and Express, and I've encountered an issue. It all runs smoothly until I attempt to utilize it with Ajax in a web browser. When I test it in Postman, everything works fi ...

Inquiry on Improving Performance with jQuery

This is the layout of my HTML structure on a page, with an AJAX response that mirrors the same structure: <div id="feeds"> <div class="items"> <div class="feedClass"> content </div> <div c ...

Achieve a smooth slide-in effect from the left for your sidebar when the button is clicked using TailwindCSS

I am currently working on a sidebar menu with a button that toggles its visibility. However, I am struggling to implement a sliding animation from the left when the sidebar appears, and a slide back to the right when it closes. This is what my code looks ...

Swapping data between two HTML files and PHP

As I work on setting up a signup form for a MikroTik hotspot, I've encountered limitations with the device not supporting PHP. In order to pass the necessary variables from the device to an external PHP page where customer data will be saved and trial ...