Rating
Version 1.01
written by Gerald Holdsworth

This is for rating things on websites, e.g. photographs. It is similar to that used by Ebay and Amazon.

Click here for a demo

Javascript for 'Rating':
// add <img src="StarDefault.gif" onload="createStars(this,maxrating)" name="basename">
// where maxrating is the maximum number of stars
// and basename is the name appended to the controls. basenamerating will be the control with the rating in
// This img element needs to be encapsulated within a div.
//
function changeStar(el,onoff)
{
 var starsrc,s,elstar;
 if (onoff==1) starsrc='StarHover.gif'; else starsrc='StarDefault.gif';
 var star=el.id;
 var stname=el.name;
 var starnum=parseInt(star.substr(stname.length));
 for (s=0;s<starnum;s++)
 {
  elstar=document.getElementById(stname+(s+1));
  if (basename(elstar.src)=="StarDefault.gif" ||
      basename(elstar.src)=="StarHover.gif") elstar.setAttribute('src',starsrc);
 }
}
function setStar(el)
{
 var s,elstar;
 var star=el.id;
 var stname=el.name;
 var starnum=parseInt(star.substr(stname.length));
 var numstar=document.getElementsByName(stname).length;
 if (starnum==parseInt(document.getElementsByName(stname+'rating')[0].value)) starnum=0;
 for (s=0;s<numstar;s++)
 {
  elstar=document.getElementById(stname+(s+1));
  if ((s+1)<=starnum)
  {
   elstar.setAttribute('src','Star.gif');
   elstar.onmouseover='';
   elstar.onmouseout='';
  }
  else
  {
   elstar.setAttribute('src','StarDefault.gif');
   elstar.onmouseover=function(){changeStar(this,1)};
   elstar.onmouseout=function(){changeStar(this,0)};
  }
 }
 document.getElementsByName(stname+'rating')[0].value=starnum;
 if (starnum==0) changeStar(el,1);
}
function createStars(el,num)
{
 var i,img;
 for (i=0;i<num;i++)
 {
  img=document.createElement('img');
  img.setAttribute('src',el.src);
  img.name=el.name;
  img.onmouseover=function(){changeStar(this,1)};
  img.onmouseout=function(){changeStar(this,0)};
  img.onclick=function(){setStar(this)};
  img.id=el.name+(i+1);
  el.parentNode.appendChild(img);
 }
 img=document.createElement('input');
 img.setAttribute('type','hidden');
 img.setAttribute('value','0');
 img.name=el.name+'rating';
 el.parentNode.appendChild(img);
 el.parentNode.removeChild(el);
}
function basename(path)
{
 return path.replace(/\\/g,'/').replace( /.*\//, '' );
}
Click here to download.

If you would like to email me, put gerald@ in front of the domain name, insead of www..
©2011-2020 Gerald Holdsworth IT Services