Welcome to a tutorial on how to create a simple star rating widget using HTML, CSS, and Javascript. Looking for a star rating script, but they are either paid or bloated with third-party libraries? Well, here’s a simple one in pure Javascript – Read on!
TABLE OF CONTENTS
JAVASCRIPT STAR RATING
All right, let us now get into the details of the Javascript star rating. This is for you guys who want to “deep customize” it.
QUICK START & DEMO
<!-- (A) LOAD STAR RATING CSS & JS -->
<link rel="stylesheet" href="2-star.css">
<script src="3-star.js"></script>
<!-- (B) GENERATE STAR RATING HERE -->
<div id="demo"></div>
<!-- (C) INIT STAR RATING -->
<script>
starry({
// (C1) REQUIRED
target: document.getElementById("demo"),
// (C2) OPTIONAL
max: 5,
now: 3,
// disabled: true,
click : stars => alert(stars)
});
// (D) TO GET NUMBER OF STARS PROGRAMMATICALLY
var stars = document.getElementById("demo").getstars();
console.log(stars);
For you guys who just want to use this as a “plugin”:
- Load the CSS and Javascript. Doh.
- Create an empty
<div>
to generate the star rating. - Call
starry()
to attach the star rating.target
The target<div>
to generate the star rating.max
Optional. The maximum number of stars, default 5.now
Optional. The current number of stars, default 0.disabled
Optional. Iftrue
, user cannot change star rating, or click to update. Defaultfalse
.click
Optional. Function to call when the user clicks on a star.
Lastly, if you want to get the selected number of stars in your own function, use document.getElementById("ELEMENT").getstars()
.
THE CSS
/* (A) CUSTOM "STAR ICON ONLY" FONT */
/* https://icomoon.io/ */
@font-face {
font-family: "icomoon";
src: url(icomoon.woff);
}
/* (B) STAR RATING WRAPPER */
.starwrap { display: flex; }
/* (C) STAR ICON */
.star {
font-family: "icomoon" !important;
font-size: 24px; color: #d1d1d1;
font-style: normal; font-weight: normal; font-variant: normal;
text-transform: none; line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.star::before { content: "\e9d9"; }
.star.on { color: #ffe000; }
First, the Javascript generates a simple:
<div id="demo" class="starwrap">
<div class="star on"></div>
<div class="star on"></div>
<div class="star on"></div>
<div class="star"></div>
<div class="star"></div>
</div>
So this should be self-explanatory.
icomoon.woff
Contains a single star icon.- We use
.star::before
to attach the star icon. .star
Is the default style for a “grey star”..star .on
Is the style for a “highlighted star”.
THE JAVASCRIPT
function starry (instance) {
// (A) SET DEFAULTS
if (instance.max === undefined) { instance.max = 5; }
if (instance.now === undefined) { instance.now = 0; }
if (instance.now > instance.max) { instance.now = instance.max; }
if (instance.disabled === undefined) { instance.disabled = false; }
// (B) GENERATE STARS
instance.target.classList.add("starwrap");
for (let i=1; i<=instance.max; i++) {
// (B1) CREATE HTML STAR
let s = document.createElement("div");
s.className = "star";
instance.target.appendChild(s);
// (B2) HIGHLIGHT STAR
if (i <= instance.now) { s.classList.add("on"); }
if (!instance.disabled) {
// (B3) ON MOUSE OVER
s.onmouseover = () => {
let all = instance.target.getElementsByClassName("star");
for (let j=0; j<all.length; j++) {
if (j<i) { all[j].classList.add("on"); }
else { all[j].classList.remove("on"); }
}
};
// (B4) ON CLICK
if (instance.click) { s.onclick = () => instance.click(i); }
}
}
// (C) GET NUMBER OF SELECTED STARS
instance.target.getstars = () => instance.target.querySelectorAll(".on").length;
}
Not going to explain this line-by-line, but essentially:
- As in the “quick start” above, this section simply sets all the default options if not specified.
- Generate the
<div class="star">
in your specified wrapper. Attachonmouseover
andonclick
. - Attach
getstars()
to the HTML element… Which does a very simple count of the number of.on
stars.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
I WANT TO INITIATE MULTIPLE INSTANCES
<div class="starwrap"></div>
<div class="starwrap"></div>
<div class="starwrap"></div>
<script>
Array.from(document.getElementsByClassName("starwrap")).forEach((div) => {
starry({ target: div });
});
</script>
Just loop through all the <div>
and attach with starry()
.
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- WOFF Font – CanIUse
Works on all modern “Grade A” browsers.
LINKS & REFERENCES
- PHP MYSQL Star Rating System – Code Boxx
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
I really appreciate youe effort