Star-Based Rating System

Kedernath Mallick.
3 min readSep 2, 2021

Many paid services are there for providing a star type rating system,which can be used a rating system in any blog for review purpose.But we can create this by ourselves.

We are going to make something like this https://keder-code-hash.github.io/StarBasedRatingSystem/starRate/

Here we have to consider some functionalities

  1. we can increase the the number of star if we want.
  2. rating (no. of star) should be visible to the user.

Design the Element:-

We here handle the total rating system by DOM(Data Object Model) Manipulation.DOM treats an XML or HTML document as a tree structure wherein each node is an object representing a part of the document.Some great advantages of using DOM,it is cross-platform and language-independent interface.

First we have to create the star which acts as a button,where any user can rate.When user rate color of star will change to yellow(by default it is black).

HTML template for the rating system.

Now we have to create the stars by DOM.we use here Window: load event which is fired when the whole page has loaded.

Now we have to handle the whole process for rating.So here we use a classname for span “clicked/notclicked”. When we click a star we access this element and find its parent node.After finding its parent node we change the notclicked class as clicked and change the color to yellow and we store this rating into a global variable for future reference.

For the first time the condition will be pretty straight Forward.

  1. clickedNode.classList.contains(“notclicked”) && currentNodeId >prevClicked

Now when a user will rate for the second time there will be two cases

  1. clickedNode.classList.contains(“clicked”)==true && currentNodeId <prevClicked
  2. clickedNode.classList.contains(“clicked”) && currentNodeId ==prevClicked

Here prevClick will keep the track of previous rating(by id) and currentNodeId will keep the track of newly clicked star.So for the first one we just change the color of star (from first to currentNodeId)to black and change the classname to notclicked.Now for the second one we we have to reset the whole star based rating system.

Here the Rate function will do the whole work for changing the color of a star and changing the classname “clicked” to “notclicked” one and vice-versa.

And it is done.😊

Star-Based review System

references

  1. https://www.w3schools.com/jsref/prop_element_classlist.asp
  2. https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
  3. https://en.wikipedia.org/wiki/Document_Object_Model

Link for whole project

--

--