Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Rate content using stars

Here are some javascript functions, that will allow your visitors to rate your content by clicking on stars. We will use same stars, that are used in display rating using stars article.

So what we will do, is define two CSS classes with full star and empty star. Then create 3 javascript function. One for onmouseover event that will change css classes for current and all previous stars, other for onmouseout event, which will change all element classes back toempty stars and third one which will generate provided amount of stars by parameter and set all default classes and events.

So here is the code:

<html>
<head>
</head>
<body>
<div id='stars'></div>
<style type='text/css'>
<!-- class with full star -->
.staron
{
    float: left;
    height: 16px;
    width: 16px;
    background-image: url(./images/stars.png);
    background-position: 0px 16px;
}
<!-- class with empty star -->
.staroff
{
    float: left;
    height: 16px;
    width: 16px;
    background-image: url(./images/stars.png);
    background-position: 0px 0px;
}
</style>
<script type='text/javascript'>
//we pass id of star where mouse cursor is
//and change class for every previous star
function star(rate)
{
    for(var i = 1; i <= rate; i++)
    {
        document.getElementById("rate_" + i).setAttribute("class", "staron");
    }
}
//we change class of all stars back to empty star
function unstar(max)
{
    for(var i = 1; i <= max; i++)
    {
        document.getElementById("rate_" + i).setAttribute("class", "staroff");
    }
}
//generate stars
//first param - amount of stars
//second param - id of div where to attach stars
function generate_stars(max, attach)
{
    //get div container
    var container = document.getElementById(attach);
    for(var i = 1; i <= max; i++)
    {
        //create star
        var div = document.createElement("div");
        div.setAttribute("class", "staroff");
        div.setAttribute("id", "rate_" + i);
        //set events
        div.setAttribute("onmouseover", "star(" + i + ")");
        div.setAttribute("onmouseout", "unstar(" + max + ")");
        //append child to contaner
        container.appendChild(div);
    }
     
}
generate_stars(5, "stars");
</script>
</body>
</html>

And here is result:

 

It is up to you how to pass rate value, you can either go to specified link and pass value through get, or generate dynamic javascript form and submit value through post.


You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus