On my website I have a page with serval results where people can bring out there rating.
With one rating list on the page everything works fine but with multiple I got a little problem by selecting the right list (this) to be hovered. Right now it's always the first list in the html code which is hovered (if I put my cursor on the second rating list first is hovering).
The html:
<ol class="rating" data-rating="4">
<li class="Arad5fQEnoZlv9E59d"><a title="Super boring" class="rate starOn" id="1">1 star</a></li>
<li class="Arad5fQEnoZlv9E59d"><a title="Boring" class="rate starOn" id="2">2 stars</a></li>
<li class="Arad5fQEnoZlv9E59d"><a title="Nice" class="rate starOn" id="3">3 stars</a></li>
<li class="Arad5fQEnoZlv9E59d"><a title="Cool" class="rate starOn" id="4">4 stars</a></li>
<li class="Arad5fQEnoZlv9E59d"><a title="Super cool!" class="rate star" id="5">5 stars</a></li>
<div class="response">Score 4 By 2 ratings</div>
</ol>
The part of my javascript who won't do the good job:
$('ol.rating li', this).hover(function(){
var id = $('a', this).attr('id');
var counter = 1;
var salt = $(this).attr('class');
console.log('ol.rating li.'+salt);
$('ol.rating li.'+salt).each(function(i){
if (id >= counter) {
$('a#'+counter).addClass("starHover");
} else {
$('a#'+counter).removeClass("starHover");
}
counter++;
});
});
Hope my question is a bit clear :)
Thanks in advance! Nick
Your code is working propertly (I just removed the this
keyword from the first line): http://jsfiddle.net/yAwZz/
You are printing class to the console which is the same for all <li>
elements. Could this be the source of confusion?
Update:
You are using same id
for multiple HTML elements which is never good idea. id
attribute must be unique element identificator.
You can use .index() and .slice() jQuery methods to simplify the code and make it work as expected without using ids. Note that I used mouseenter event instead of hover ad hover is called on both mouseenter and mouseleave which is in this case unnecessary:
$('ol.rating li').mouseenter(function(){
var $lis = $(this).siblings("li").andSelf();
var id = $(this).index();
$lis.removeClass("starHover");
$lis.slice(0, id + 1).addClass("starHover");
});
You can see the code working on jsfiddle: http://jsfiddle.net/yAwZz/5/