Table of Contents
Key Takeaways
Star Rating Control
Conclusion
Frequently Asked Questions (FAQs) about jQuery Star Rating
How Can I Customize the Appearance of the Star Rating?
Can I Use Half-Star Ratings in jQuery Star Rating?
How Can I Save the User’s Rating?
How Can I Display the Average Rating?
Can I Disable the Star Rating?
How Can I Use Different Star Icons?
Can I Use jQuery Star Rating Without jQuery?
How Can I Reset the Star Rating?
Can I Use jQuery Star Rating in a Form?
How Can I Handle Errors in jQuery Star Rating?
Home Web Front-end JS Tutorial Star Rating Control with jQuery

Star Rating Control with jQuery

Mar 10, 2025 am 01:00 AM

Star Rating Control with jQuery

Key Takeaways

  • The article provides a detailed guide on how to build an interactive star rating widget using jQuery. It involves creating a radio button group that is replaced by star icons, which the user can interact with to provide a rating.
  • The star rating system is designed to be keyboard-accessible and allows for half-star ratings. This is achieved by using a CSS sprite image and manipulating the background-position property to display different states of the star.
  • The rating system is designed to encourage user engagement and thoughtful rating selection by limiting the scale to four stars instead of five, thereby eliminating a middle option. It also allows for half-star ratings for greater precision.
  • The system uses jQuery to handle user interactions, including hovering and clicking on the stars. When a star is clicked, the corresponding radio button value is updated, and the star and all preceding stars are highlighted. The system also implements error handling to manage potential issues.

Our newly released book, jQuery: Novice to Ninja, contains a wealth of great ready-to-use solutions, and teaches you both the basic and more advanced concepts of jQuery as you progress. As a taster, here’s an excerpt wherein Craig Sharkie shows us how to build a robust, sophisticated star rating widget using jQuery. It’s keyboard-accessible, and allows for half-star ratings.

If you’ve never used jQuery before, grab the free sample PDF and get up to speed with the introduction in Chapter 2. Chapter 7, from which this article is taken, is also included in the download, so if you’d rather read this tutorial offline, you can do so at your leisure.

You can get the sample code archive for this article here.

Star Rating Control

Our client wants to increase user engagement, and help his users feel important. We’ve thought about this a bit, and tossed him a star rating idea—after all, people love nothing more than to express their feelings through the assignment of gold stars. Our shiny new control will appear as shown in Figure 1, “Star rating control”.

Figure 1. Star rating control

Star Rating Control with jQuery

The basis for our star rating control is a radio button group; it’s perfect, as the browser enforces a single selection from the group. You can select the range that you want the user to choose from, simply by adding the correct number of buttons:

Example 1. chapter_07/11_star_ratings/index.html (excerpt)

<div >  <label><input  name="rating" type="radio" value="1"/>1 Star</label>  <label><input  name="rating" type="radio" value="2"/>2 Stars</label>  <label><input  name="rating" type="radio" value="3"/>3 Stars</label>  <label><input  name="rating" type="radio" value="4"/>4 Stars</label>  ⋮</div>

The hard part, of course, is replacing these radio buttons with our star control. You can try to grapple with styling the HTML controls with only CSS, but it will be much easier and more flexible if you split the control into two parts: the underlying model that stores the data, and the shiny view with stars. The model, in this case, is the original HTML radio button group. Our plan of attack is to hide the radio buttons, and display a list of links that we’ve added via jQuery, styled to look like stars. Interacting with the links will switch the selected radio button. Users without JavaScript will simply see the radio buttons themselves, which is fine by us.

For the stars, we will rely on CSS sprites. This way our control will only be reliant on a single image (shown in Figure 2, “Star CSS sprite image”), which saves on HTTP requests and makes it easier for our graphic designers to edit.

Figure 2. Star CSS sprite image

Star Rating Control with jQuery

Our CSS will apply the CSS sprite image to the links we create that represent half-stars. To move between the different image states, we just need to update the background-position property:

Example 2. chapter_07/11_star_ratings/stars.css (excerpt)

.stars div a {  background: transparent url(sprite_rate.png) 0 0 no-repeat;  display: inline-block;  height: 23px;  width: 12px;  text-indent: -999em;  overflow: hidden;}.stars a.rating-right {  background-position: 0 -23px;  padding-right: 6px;}.stars a.rating-over { background-position: 0 -46px; }.stars a.rating-over.rating-right { background-position: 0 -69px; }.stars a.rating { background-position: 0 -92px; }.stars a.rating.rating-right { background-position: 0 -115px; }

We’ve decided to make the user select a rating out of four stars, rather than the usual five. Why? User psychology! Offer a person a middle road and they’ll take it; by having no middle we make the users think a bit more about their selection. We achieve better results, and we’ll be better able to present users with the best content (as chosen by them)!

But four is a limited scale—that’s why we want to allow for half-star ratings. This is implemented via an optical illusion—you probably noticed that our star images are chopped in half. Our HTML will contain eight radio buttons, and they’ll each be worth half a star. There’s two parts to the code for transforming our eight radio buttons into four stars. First, the createStars function will take a container with radio buttons and replace it with star links. Each star will then be supplemented with the proper event handlers (in the addHandlers method) to let the user interact with the control. Here’s the skeleton of our starRating object:

Example 3. chapter_07/11_star_ratings/script.js (excerpt)

var starRating = {  create: function(selector) {    $(selector).each(function() {      // Hide radio buttons and add star links    });  },  addHandlers: function(item) {    $(item).click(function(e) {      // Handle star click    })    .hover(function() {      // Handle star hover over    },function() {      // Handle star hover out    });  }}

The create method iterates through each container matching the selector we pass in, and creates a list of links that act as a proxy for the radio buttons. These links are what we’ll style to look like stars. It will also hide the original form elements, so the user only sees our lovely stars:

Example 4. chapter_07/11_star_ratings/script.js (excerpt)

<div >  <label><input  name="rating" type="radio" value="1"/>1 Star</label>  <label><input  name="rating" type="radio" value="2"/>2 Stars</label>  <label><input  name="rating" type="radio" value="3"/>3 Stars</label>  <label><input  name="rating" type="radio" value="4"/>4 Stars</label>  ⋮</div>

We start by creating a container for the new links (a div element); we’ll be creating one new link for each of the radio buttons we’re replacing. After selecting all the radio buttons with the :radio selector filter, we take each item’s rating and use it to create a hyperlink element.

note: Conditional Assignment with Modulus

For the addClass action, we’re specifying the class name conditionally with a ternary operator, based on a bit of math. As we’ve done earlier in the book, we’re using the modulus (%) operator to determine whether the index is even or odd. If the index is odd, we’ll add the rating-right class; this makes the link look like the right side of a star.

Once our link is ready, we pass it to the addHandlers method—this is where we’ll attach the events it needs to work. Then, we append it to the list container. Once it’s in the container, we see if the current radio button is selected (we use the :checked form filter). If it’s checked, we want to add the rating class to this half-star, and to all of the half-stars before it. Any link with the rating class attached will be assigned the gold star image (which will allow users to see the current rating).

To select all of the elements we need to turn gold, we’re going to enlist the help of a couple of new jQuery actions: prevAll and andSelf. The prevAll action selects every sibling before the current selection (unlike the prev action, which only selects the immediately previous sibling). For our example, we want to add the class to the previous siblings and the current selection. To do so, we apply the andSelf action, which simply includes the original selection in the current selection. Now we have all of the links that will be gold, so we can add the class.

tip: Other Traversal Methods

You might have guessed that, along with prevAll, jQuery provides us with a nextAll method, which grabs all of an element’s siblings occurring after it in the same container. jQuery 1.4 has also introduced two new companion methods: prevUntil and nextUntil. These are called with a selector, and will scan an element’s siblings (forwards or backwards, depending on which one you’re using) until they hit an element that matches the selector.

So, for example, $('h2:first').nextUntil('h2'); will give you all the elements sitting between the first h2 on the page and the following h2 in the same container element.

If you pass a second parameter to prevUntil or nextUntil, it will be used as a selector to filter the returned elements. So, for example, if we had written nextUntil('h2', 'div'), it would only return div elements between our current selection and the next h2.

After doing all this hard work, we can now add the new list of links to the control, and get rid of the original buttons. Now the user will only interact with the stars:

Example 5. chapter_07/11_star_ratings/script.js (excerpt)

<div >  <label><input  name="rating" type="radio" value="1"/>1 Star</label>  <label><input  name="rating" type="radio" value="2"/>2 Stars</label>  <label><input  name="rating" type="radio" value="3"/>3 Stars</label>  <label><input  name="rating" type="radio" value="4"/>4 Stars</label>  ⋮</div>

The control looks like it’s taking shape now—but it doesn’t do anything yet. We need to attach some event handlers and add some behavior. We’re interested in three events. When users hover over a star, we want to update the CSS sprite to show the hover state; when they move away, we want to revert the CSS sprite to its original state; and when they click, we want to make the selection gold:

Example 6. chapter_07/11_star_ratings/script.js (excerpt)

.stars div a {  background: transparent url(sprite_rate.png) 0 0 no-repeat;  display: inline-block;  height: 23px;  width: 12px;  text-indent: -999em;  overflow: hidden;}.stars a.rating-right {  background-position: 0 -23px;  padding-right: 6px;}.stars a.rating-over { background-position: 0 -46px; }.stars a.rating-over.rating-right { background-position: 0 -69px; }.stars a.rating { background-position: 0 -92px; }.stars a.rating.rating-right { background-position: 0 -115px; }

The hover function is the easiest: when hovering over, we select all of the half-stars before—including the current half-star—and give them the rating-over class using prevAll and andSelf, just like we did in the setup. When hovering out, we cover our bases and remove the rating-over class from all of the links. That’s hovering taken care of.

Now for the click:

Example 7. chapter_07/11_star_ratings/script.js (excerpt)

var starRating = {  create: function(selector) {    $(selector).each(function() {      // Hide radio buttons and add star links    });  },  addHandlers: function(item) {    $(item).click(function(e) {      // Handle star click    })    .hover(function() {      // Handle star hover over    },function() {      // Handle star hover out    });  }}

The important part of handling the click event is to update the underlying radio button model. We do this by selecting the correct radio button with the :radio filter and an attribute selector, which searches for the radio button whose value matches the current link’s text.

With the model updated, we can return to messing around with the CSS sprites. First, we clear the rating class from any links that currently have it, then add it to all of the links on and before the one the user selected. The last touch is to cancel the link’s default action, so clicking the star doesn’t cause it to fire a location change.

Conclusion

I hope you’ve enjoyed this taste of all the jQuery goodness that’s contained in jQuery: Novice to Ninja. Remember to grab your free sample PDF, which contains this example as well as 150 pages worth of more great learning material. If you’re already sold, you can go ahead and buy the book straight from SitePoint.

Frequently Asked Questions (FAQs) about jQuery Star Rating

How Can I Customize the Appearance of the Star Rating?

Customizing the appearance of the star rating can be achieved by modifying the CSS. You can change the color, size, and spacing of the stars. For instance, to change the color, you can use the ‘color’ property in your CSS. To change the size, you can adjust the ‘font-size’ property. Remember to target the specific class of your star rating in your CSS to apply these changes.

Can I Use Half-Star Ratings in jQuery Star Rating?

Yes, you can use half-star ratings in jQuery Star Rating. This can be achieved by setting the ‘half’ option to true when initializing the star rating. This allows for more precise ratings, giving users the ability to rate with half stars.

How Can I Save the User’s Rating?

To save the user’s rating, you can use AJAX to send the rating value to a server-side script. This script can then store the rating in a database. When the page is loaded, the script can retrieve the stored rating and display it.

How Can I Display the Average Rating?

Displaying the average rating can be done by calculating the average of all stored ratings and then setting the value of the star rating to this average. This can be done using a server-side script that retrieves all ratings from the database, calculates the average, and then sends this average back to the client-side script.

Can I Disable the Star Rating?

Yes, you can disable the star rating. This can be useful if you want to display a rating but don’t want users to be able to change it. To disable the star rating, you can set the ‘readOnly’ option to true when initializing the star rating.

How Can I Use Different Star Icons?

You can use different star icons by changing the ‘starOff’ and ‘starOn’ options when initializing the star rating. These options accept the names of the icons you want to use. The icons should be part of a font icon set that is included in your project.

Can I Use jQuery Star Rating Without jQuery?

jQuery Star Rating is a jQuery plugin, so it requires jQuery to function. If you want to use a star rating without jQuery, you will need to find a different solution, such as a pure JavaScript star rating library.

How Can I Reset the Star Rating?

You can reset the star rating by setting its value to 0. This can be done using the ‘rating’ method of the star rating instance. For example, if your star rating instance is stored in a variable named ‘rating’, you can reset it with ‘rating.rating(0)’.

Can I Use jQuery Star Rating in a Form?

Yes, you can use jQuery Star Rating in a form. The star rating can be linked to a hidden input field in the form. When the user submits the form, the value of the star rating will be included in the form data.

How Can I Handle Errors in jQuery Star Rating?

Handling errors in jQuery Star Rating can be done using the ‘error’ event. This event is triggered when there is an error in the star rating, such as when an invalid value is set. You can listen for this event and then handle the error in a way that is appropriate for your application.

The above is the detailed content of Star Rating Control with jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Advanced Conditional Types in TypeScript Advanced Conditional Types in TypeScript Aug 04, 2025 am 06:32 AM

TypeScript's advanced condition types implement logical judgment between types through TextendsU?X:Y syntax. Its core capabilities are reflected in the distributed condition types, infer type inference and the construction of complex type tools. 1. The conditional type is distributed in the bare type parameters and can automatically split the joint type, such as ToArray to obtain string[]|number[]. 2. Use distribution to build filtering and extraction tools: Exclude excludes types through TextendsU?never:T, Extract extracts commonalities through TextendsU?T:Never, and NonNullable filters null/undefined. 3

Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Aug 05, 2025 am 08:30 AM

This article explores in-depth how to automatically generate solveable puzzles for the Double-Choco puzzle game. We will introduce an efficient data structure - a cell object based on a 2D grid that contains boundary information, color, and state. On this basis, we will elaborate on a recursive block recognition algorithm (similar to depth-first search) and how to integrate it into the iterative puzzle generation process to ensure that the generated puzzles meet the rules of the game and are solveable. The article will provide sample code and discuss key considerations and optimization strategies in the generation process.

How can you remove a CSS class from a DOM element using JavaScript? How can you remove a CSS class from a DOM element using JavaScript? Aug 05, 2025 pm 12:51 PM

The most common and recommended method for removing CSS classes from DOM elements using JavaScript is through the remove() method of the classList property. 1. Use element.classList.remove('className') to safely delete a single or multiple classes, and no error will be reported even if the class does not exist; 2. The alternative method is to directly operate the className property and remove the class by string replacement, but it is easy to cause problems due to inaccurate regular matching or improper space processing, so it is not recommended; 3. You can first judge whether the class exists and then delete it through element.classList.contains(), but it is usually not necessary; 4.classList

Vercel SPA routing and resource loading: Solve deep URL access issues Vercel SPA routing and resource loading: Solve deep URL access issues Aug 13, 2025 am 10:18 AM

This article aims to solve the problem of deep URL refresh or direct access causing page resource loading failure when deploying single page applications (SPAs) on Vercel. The core is to understand the difference between Vercel's routing rewriting mechanism and browser parsing relative paths. By configuring vercel.json to redirect all paths to index.html, and correct the reference method of static resources in HTML, change the relative path to absolute path, ensuring that the application can correctly load all resources under any URL.

Vercel Single Page Application (SPA) Deployment Guide: Solving Deep URL Asset Loading Issues Vercel Single Page Application (SPA) Deployment Guide: Solving Deep URL Asset Loading Issues Aug 13, 2025 pm 01:03 PM

This tutorial aims to solve the problem of loading assets (CSS, JS, images, etc.) when accessing multi-level URLs (such as /projects/home) when deploying single page applications (SPAs) on Vercel. The core lies in understanding the difference between Vercel's routing rewriting mechanism and relative/absolute paths in HTML. By correctly configuring vercel.json, ensure that all non-file requests are redirected to index.html and correcting asset references in HTML as absolute paths, thereby achieving stable operation of SPA at any depth URL.

The Module Pattern in JavaScript: A Practical Guide The Module Pattern in JavaScript: A Practical Guide Aug 05, 2025 am 09:37 AM

ThemodulepatterninjavascriptsolvestheProbllobalscopepollutionandandandandandandandandandlackofencapsulation byusingClosuresandiifestocreatePrivat EvariaBlesandExPosonTrolledPublicapi; 1) IthidesInternal DataStusersandvalidatenamewithinacloslosloslosloslosloslus

Qwik: A Resumable Framework for Instant-Loading Web Apps Qwik: A Resumable Framework for Instant-Loading Web Apps Aug 15, 2025 am 08:25 AM

Qwikachievesinstantloadingbydefaultthroughresumability,nothydration:1)TheserverrendersHTMLwithserializedstateandpre-mappedeventlisteners;2)Norehydrationisneeded,enablingimmediateinteractivity;3)JavaScriptloadson-demand,onlywhenuserinteractionoccurs;4

js add element to start of array js add element to start of array Aug 14, 2025 am 11:51 AM

In JavaScript, the most common method to add elements to the beginning of an array is to use the unshift() method; 1. Using unshift() will directly modify the original array, you can add one or more elements to return the new length of the added array; 2. If you do not want to modify the original array, it is recommended to use the extension operator (such as [newElement,...arr]) to create a new array; 3. You can also use the concat() method to combine the new element array with the original number, return the new array without changing the original array; in summary, use unshift() when modifying the original array, and recommend the extension operator when keeping the original array unchanged.

See all articles