Reputation: 15
I have a simple rating stars script as given below. My problem is that once the user has put in his vote, he cannot change his vote (if he has a change of mind and wants to change his vote before submitting). My script goes as follows:
$(function() {
$('a').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('hoverstar');
$(this).nextAll().removeClass('visited');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('hoverstar');
$(this).nextAll('a').removeClass('hoverstar');
$(this).nextAll('a').removeClass('visited');
}
);
$('a').click(
function() {
$(this).prevAll('a').andSelf().addClass('visited');
$(this).nextAll('a').removeClass('visited');
}
);
});
The style-sheet is as follows:
.rate_widget ul
{
background: url('star-white16.gif') repeat-x;
}
.rate_widget a.visited{
background: url('star-red16.gif') repeat-x;
}
.rate_widget a.hoverstar{
background: url('star-gold16.gif') repeat-x;
}
The stars are displayed as links as follows:
<div class='rate_widget'>
<ul>
<li><a href='#' class='one-star' id="1">1</a></li>
<li><a href='#' class='two-stars' id="2">2</a></li>
<li><a href='#' class='three-stars' id="3">3</a></li>
<li><a href='#' class='four-stars' id="4">4</a></li>
<li><a href='#' class='five-stars' id="5">5</a></li>
</ul>
</div>
Upvotes: 1
Views: 577
Reputation: 1768
I have a pretty simple rating system that will communicate with PHP just fine if you add the $post()
in place of the alert. The thing to notice is the star graphic is an inverted PNG.
.star {
float: left;
width: 21px;
height: 20px;
background-image: url('http://www.libertyeaglearms.com/graphics/star.png');
}
The area outside the star is white so when you change the background color via css the star appears to change color. Take a look and see if this will work for ya.
Upvotes: 0
Reputation: 2251
This isn't the best of code, but it should put you on the right track:
$('a').click(
function() {
if ($(this).parent().parent().attr('voted') !== '1') {
$(this).prevAll('a').andSelf().addClass('visited');
$(this).nextAll('a').removeClass('visited');
$(this).parent().parent().attr('voted', '1');
}
}
);
Essentially what it does is when a click is done to vote it adds an attribute "voted" to the UL element. When clicked again if that value is set then it does not allow a vote to happen again. You would need to check against this when hovering as well so that it does not highlight the stars again.
Ideally you would want something neater than .parent().parent()
. If you have a single star rating on the page rather use an id.
Upvotes: 1