Wednesday 16 September 2009

A JS/CSS based star rating system for web pages

I was working on a project tonight that needed a "star" rating system and I had one from a while ago that you may find useful.

It works like this.

I have an image that is 20px wide and 40px deep
In the top 20x20px I have an empty star
In the bottom 20x20px I have a selected star like this

If I place this image as a background in a block type element sized 20x20px with a CSS style of background-position: left top; the user will be presented with the empty star. If on the other hand I position it with the CSS of background-position: left bottom; you will see the selected star.

So all I need to do now is create an HTML
(1) that has a hidden field for me to store the value that will relate to the number of stars selected
(2) that has a table were each cell is sized to be 20x20px
(3) where each cell has CSS with a background-image of my star picture
(4) where each cell as an onmouseover event that changes the css so that the background image's css is changed to be the bottom portion of the background image.

If it all works you will get something like this (sorry it is off site.. but blogger wouldnt play ball with the JS)

The code for the page in the link above looks like this . feel free to take and use as you see fit.. however if you do drop me a comment.. I like to feel i am being useful ;-)

background-image: url(star_rating.gif);
background-position: top left;
width: 20px;
height: 20px;
cursor: pointer;
<script = 'javascript'>
function star(a)
// reset all stars to blank
for(var t=1;t<=5;t++)
document.getElementById(t+"star").style.backgroundPosition="left top";
// Set new value in hidden field
// Set new value for display
for(var t=1;t<=parseInt(a);t++)
document.getElementById(t+"star").style.backgroundPosition="left bottom";
<body onload="star(3)">
This field below normaly be hidden <br>
<input type='text' id='likeem' name='likeem' value=""><br>
Now move your mouse over the stars below</br>

<table cellspacing='0' cellpadding='0' border='0'>
<td id='1star' class='star' onmouseover= "star(1)"></td>
<td id='2star' class='star' onmouseover= "star(2)"></td>
<td id='3star' class='star' onmouseover= "star(3)"></td>
<td id='4star' class='star' onmouseover= "star(4)"></td>
<td id='5star' class='star' onmouseover= "star(5)"></td>


Disqus for Domi-No-Yes-Maybe