What are the steps to create a basic star-rating system?

I attempted to create my own star rating system using HTML and CSS, but encountered issues with its functionality. While solutions like using direction: rtl or float: right worked, I am unable to implement them due to constraints related to PHP.

Is there a way to achieve the desired outcome using only CSS and HTML?

$('.stars a').on('click', function(){
$('.stars a').removeClass('active');
$(this).addClass('active');
});
.stars input {
    position: absolute;
    left: -999999px;
}

.stars a {
    display: inline-block;
    font-size: 0;
    text-decoration: none;
}

.stars a:before {
    position: relative;
    font-size: 18px;
    font-family: 'FontAwesome', serif;
    display: block;
    content: "\f005";
    color: #9e9e9e;
}

.stars a:hover:before,
.stars a:hover ~ a:before,
.stars a.active:before,
.stars a.active ~ a:before {
    color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<p class="stars">
  <span>
    <a class="star-1" href="#">1</a>
    <a class="star-2" href="#">2</a>
    <a class="star-3" href="#">3</a>
    <a class="star-4" href="#">4</a>
    <a class="star-5" href="#">5</a>
  </span>
</p>

Answer №1

When working on the HTML, I noticed an interesting color change that could be reversed using pure CSS. The issue lies in the fact that + and ~ selectors only work on next elements, which is why I suggested making the next a element gray instead of blue.

I attempted to manipulate the CSS alone, but eventually had to introduce a new class to the span element to address the active state. My solution resulted in the following code:

$('.stars a').on('click', function(){
  $('.stars span, .stars a').removeClass('active');

  $(this).addClass('active');
  $('.stars span').addClass('active');
});
.stars input {
    position: absolute;
    left: -999999px;
}

.stars a {
    display: inline-block;
    padding-right:4px;
    text-decoration: none;
    margin:0;
}

.stars a:after {
    position: relative;
    font-size: 18px;
    font-family: 'FontAwesome', serif;
    display: block;
    content: "\f005";
    color: #9e9e9e;
}


span {
  font-size: 0; /* trick to remove inline-element's margin */
}

.stars a:hover ~ a:after{
  color: #9e9e9e !important;
}
span.active a.active ~ a:after{
  color: #9e9e9e;
}

span:hover a:after{
  color:blue !important;
}

span.active a:after,
.stars a.active:after{
  color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<p class="stars">
  <span>
    <a class="star-1" href="#">1</a>
    <a class="star-2" href="#">2</a>
    <a class="star-3" href="#">3</a>
    <a class="star-4" href="#">4</a>
    <a class="star-5" href="#">5</a>
  </span>
</p>

Hopefully this solution proves helpful! :)

Answer №2

This method utilizes radio buttons to create the desired outcome

<h1>CSS Star Rating System</h1>
<fieldset class="rating">
    <input type="radio" id="star5" name="rating" value="5" /><label class = "full" for="star5" title="Excellent - 5 stars"></label>
    <input type="radio" id="star4half" name="rating" value="4 and a half" /><label class="half" for="star4half" title="Very good - 4.5 stars"></label>
    <input type="radio" id="star4" name="rating" value="4" /><label class = "full" for="star4" title="Very good - 4 stars"></label>
    <input type="radio" id="star3half" name="rating" value="3 and a half" /><label class="half" for="star3half" title="Okay - 3.5 stars"></label>
    <input type="radio" id="star3" name="rating" value="3" /><label class = "full" for="star3" title="Okay - 3 stars"></label>
    <input type="radio" id="star2half" name="rating" value="2 and a half" /><label class="half" for="star2half" title="Not great - 2.5 stars"></label>
    <input type="radio" id="star2" name="rating" value="2" /><label class = "full" for="star2" title="Not great - 2 stars"></label>
    <input type="radio" id="star1half" name="rating" value="1 and a half" /><label class="half" for="star1half" title="Poor - 1.5 stars"></label>
    <input type="radio" id="star1" name="rating" value="1" /><label class = "full" for="star1" title="Terrible - 1 star"></label>
    <input type="radio" id="starhalf" name="rating" value="half" /><label class="half" for="starhalf" title="Abysmal - 0.5 stars"></label>
</fieldset>

Visit this link for more information

Answer №3

Creating a user-friendly star rating system using only javascript.

HTML

<div id="rating_bar"> </div>

CSS

#rating_bar {
    width:100px;
    height:100px;
    display:inline-block;
    display:inline;
}

Javascript

var content ='';
  for(var i=1;i<=5;i++)
  content += ' <span id="rate_'+i+'">✰</span> ';
document.getElementById('rating_bar').innerHTML=content;
 
var spans = document.getElementById("rating_bar")
.getElementsByTagName('span');
for(i=0;i<spans.length;i++)
  spans[i].onmouseover=hoverStar;
  
function hoverStar() 
{
  for(i=0;i<this.id.charAt(5);i++)
    spans[i].innerText='⭐';
  for(i=this.id.charAt(5);i<5;i++)
    spans[i].innerText='✰';
}

Sample Output:

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

Answer №4

HTML

    <div class="rating" tabindex="1" onblur="calculateRating(this)">
      <i class="fa fa-star-o" aria-hidden="true" value="1" onclick="clickStar(this)"></i>
      <i class="fa fa-star-o" aria-hidden="true" value="2" onclick="clickStar(this)"></i>
      <i class="fa fa-star-o" aria-hidden="true" value="3" onclick="clickStar(this)"></i>
      <i class="fa fa-star-o" aria-hidden="true" value="4" onclick="clickStar(this)"></i>
      <i class="fa fa-star-o" aria-hidden="true" value="5" onclick="clickStar(this)"></i>
    </div>
    <div class="rating-display"></div>

CSS

.clicked{
color:yellow;}

JAVASCRIPT

var rating = document.querySelector(".rating");
var ratingDisplayEle = document.querySelector(".rating-display");

//add event listener
function clickStar(ele){
  var clickedStar = ele;
  //value of the star
  var ratingValue = parseInt(clickedStar.getAttribute("value"));
  //change the color of the star
  for(var i=0; i<ratingValue; i++){
    rating.children[i].classList.add("clicked");
    for(var j=ratingValue; j<=4; j++){
      if(rating.children[j].classList.contains("clicked")){
        rating.children[j].classList.remove("clicked");
      }
    }
  }
}

//function to calculate rating
function calculateRating(ele){
  //check how many elements are having clicked class
  var ratingCount = 0;
  for(var i=0; i<ele.children.length; i++){
    if(ele.children[i].classList.contains("clicked")){
      ratingCount++;
    }
  }
  ratingDisplayEle.textContent = `You have selected ${ratingCount} rating out of 5`;
}

Answer №5

A Simple Star Rating System

function updateRating() {
var fiveStar = document.getElementById('1-star').checked;
document.getElementById("one").innerHTML = fiveStar;

}
/* CSS for star rating component */

.star-rating {
  
  display:flex;
  flex-direction: row-reverse;
  font-size:3em;
  justify-content:space-around;
  padding:0 .2em;
  text-align:center;
  width:5em;
}

.star-rating input {
  display:none;
}

.star-rating label {
  color:#ccc;
  cursor:pointer;
}

.star-rating :checked ~ label {
  color:#f90;
}

.star-rating label:hover,
.star-rating label:hover ~ label {
  color:#fc0;
}
<div class="star-rating">
  <input type="radio" id="5-stars" name="rating" value="5" />
  <label for="5-stars" class="star">&#9733;</label>
  <input type="radio" id="4-stars" name="rating" value="4" />
  <label for="4-stars" class="star">&#9733;</label>
  <input type="radio" id="3-stars" name="rating" value="3" />
  <label for="3-stars" class="star">&#9733;</label>
  <input type="radio" id="2-stars" name="rating" value="2" />
  <label for="2-stars" class="star">&#9733;</label>
  <input type="radio" id="1-star" name="rating" value="1" />
  <label for="1-star" class="star">&#9733;</label>
</div>
<p id="one" onclick="updateRating()">Click me to change my HTML content (innerHTML).</p>

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

Is it possible to determine if the process for changing Three.js material has been successfully completed?

Is it possible to determine the completion of this process? material.map = new THREE.Texture( canvas ); material.map.needsUpdate = true; If not, sometimes the final result will be a black snapshot. var snapshotData = renderer.domElement.toDataURL(strMi ...

What is the process of canceling a load or updating a page in jQuery Mobile?

How can I prevent loading or changing pages in the pagebeforecreate event for jQuery Mobile? Is there a specific function within jQuery Mobile that can achieve this? ...

Sending FormData from React.js to an Express.js backend results in loss of data

I encountered a problem while developing a book library management CRUD system using React v18. The issue arises when attempting to add data to my MongoDB Atlas database. Whenever I pass the formData to axios.post through Redux, the req.body on the backend ...

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...

Boxes not occupying entire vertical space

My structure is unique, like a 9-box with div elements: <div class="NBWrapper"> <div class="NBTopRow"> <div class="NBLeft" /> <div class="NBRight" /> <div class="NBMiddle" /> </div> & ...

Unique Menu: Challenge when adjusting the width of 5 divs upon hovering while maintaining full site width at 100%

I'm looking to create a sleek custom menu with 5 fields. I want the field under the mouse to expand in width on mouseover, while the other fields shrink in width. The issue I'm facing is that the transition effect is not smooth and the total wid ...

What is the method for editing individual rows in a data table in Spring MVC when the edit button is clicked?

Every time I click on <a id="myBtn"><i class="fa fa-pencil" style="color:OliveDrab;"></i></a>, I only get a modal on the first row click, and it appears empty. I've searched through many internet resources, but none of them pro ...

Guide on hosting Google's Material Design Icon-Fonts on your personal server and incorporating them into your website

To access the Material Design Icon Fonts, it is advised to download them in various formats such as ttf, eot, woff, and woff2. These fonts can then be hosted on a server location and integrated into your CSS using the following code: @font-face { font- ...

Spin a sphere by clicking on a link using three.js

I've designed a spherical object and have a group of links. I'm looking for a way to manipulate the position or rotation of the sphere by simply clicking on one of the links. Despite extensive searching, I haven't been able to find an exampl ...

The most effective method for monitoring updates to an array of objects in React

Imagine a scenario where an array of objects is stored in state like the example below: interface CheckItem { label: string; checked: boolean; disabled: boolean; } const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined ...

PHP script not being triggered by Ajax upload

After identifying and fixing errors through the Chrome console log, I am facing a new issue where the PHP script responsible for processing the data is not being called. <legend><strong>Choose a machine model</strong></legend> < ...

Tips for asynchronously updating a model in TypeScript

I have been working on a function to hide the element for connecting to Facebook upon successful connection. I have implemented two functions, success and error, which trigger after Firebase successfully logs in the user. While I can confirm that these fun ...

Updating the CSS class for a particular text segment enclosed in a <p> or <span> element

My <p> tag is set to contain several lines of text with a specific CSS class, but I am looking to modify the text format within certain parts of the paragraph. In the past, I would achieve this using the <font> tag, however it seems that HTML5 ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

After clicking multiple times within the modal, the modal popup begins to shift towards the left side

I successfully implemented a modal popup in my project, but encountered an issue where the popup moves to the left side if clicked multiple times. Despite searching extensively online, I have not been able to find a solution to this problem. Below is the ...

What could be causing the issue with the functionality of third-level nested SortableJS drag-and-drop?

I am currently utilizing SortableJS to develop a drag-and-drop form builder that consists of three types/levels of draggable items: Sections, Questions, and Options. Sections can be dragged and reorganized amongst each other, Questions can be moved within ...

What is the best way to showcase SVG code as an image using Vuejs?

My API is returning an SVG image as ASCII text code, which I am trying to display on my page. However, instead of the image, I just see a blank space. You can view my attempted solution in this JSFiddle: https://jsfiddle.net/c0p4ku78/ The key parts of th ...

Creating a wider background color for active nav bar links in CSS - A step-by-step guide

I've been working on customizing a CSS navbar and I've managed to get it to work as desired. However, I'm facing an issue with the active state background color, which seems to be the same width as the text itself. I've spent hours sear ...

Locate the destination URL in Fancybox

Is there a way to insert a link into the title, using the selected anchor's href but with an added prefix? I need help figuring out how to achieve this. Specifically, I am looking to access this.href on the chosen anchor element. $(".gallery-module & ...

Modifying CSS files in real-time

I've been attempting to dynamically change the CSS file, but I've run into an issue: Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function ...