I am working on a star rating option. I have a span containing a hidden input and five images. When one of the image is hovered over, that image and every sibling image to the left is set to the a highlighted version of the image and every sibling to the right is dimmed.
The HTML
<span>
<input type="hidden" value="1" class="starCount">
<img src="star-on.jpg" alt="Rating:1 Star" class="rating"><!--
--><img src="star-off.jpg" alt="Rating:2 Stars" class="rating"><!--
--><img src="star-off.jpg" alt="Rating:3 Stars" class="rating"><!--
--><img src="star-off.jpg" alt="Rating:4 Stars" class="rating"><!--
--><img src="star-off.jpg" alt="Rating:5 Stars" class="rating">
</span>
The JQuery
click: (function(){
// Set the hidden input value to which rating you clicked
$(this).siblings(".starCount:eq(0)").val($(this).index());
}),
mouseover: (function(){
// Highlight the star being hovered + all stars to the left
$(this).attr("src","star-on.jpg");
$(this).prevAll(".rating").attr("src","star-on.jpg");
$(this).nextAll(".rating").attr("src","star-off.jpg");
}),
mouseout:(function(){
// Reset highlighted stars to the value of the hidden input
// Get the position of the hovered element
var stars = parseInt($(this).siblings(".starCount:eq(0)").val());
if($(this).index() != stars){
// Highlight this element and everything to it's left
$(this).siblings(".rating:lt("+(stars-1)+")").attr("src","star-on.jpg");
// Dim everything to the right
/* -- Note this line: It works, but is where my question derives from -- */
$(this).siblings(".rating:eq("+(stars-1)+")").nextAll().attr("src","star-off.jpg");
}
})
My problem is how I had to accomplish the “dimming” portion. This works for [this element] + previous siblings:
$(this).siblings(".rating:lt("+(stars-1)+")").attr("src","star-on.jpg");
Why does this not work properly for everything after:
$(this).siblings(".rating:gt("+(stars-1)+")").attr("src","star-off.jpg");
I just noticed that I didn’t explain what is not working when using the GT selector. Here’s how I can reproduce my issue.
See http://jsfiddle.net/SNmcB/1/:
- Click the third star.
- Mouse over star 1 and back out; it resets back to 3 selected.
- Click the first star.
- Mouse over star 4 or 5 and back out; the star you were hovered over remains highlighted.
- If I use the nextAll() method instead of GT, this behavior doesn’t happen.
The first star’s siblings are: 2 3 4 5
There is no gt() selector that can select this.
The second star’s siblings are: 1 3 4 5
The gt parameter needs to be 0.
Star #3
Siblings: 1 2 4 5
index needed: 1
Star #4
Siblings: 1 2 3 5
index needed: 2
Star #5
Siblings: 1 2 3 4
index needed: 3
So the following should work: