Vaia Vaia - 4 months ago 10
jQuery Question

Fill up previous stars on a JQuery 5-star rating onmouseover system

I want to implement a 5 star rating system and fill up the stars left from the mouseover position yellow (class called

yellow
), otherwise
grey
.

I have done this so far:

HTML:

<div id="stars3">
<i data-count="0" class="glyphicon glyphicon-star grey-light grey"></i>
<i data-count="1" class="glyphicon glyphicon-star grey-light grey"></i>
<i data-count="2" class="glyphicon glyphicon-star grey-light grey"></i>
<i data-count="3" class="glyphicon glyphicon-star grey-light grey"></i>
<i data-count="4" class="glyphicon glyphicon-star grey-light grey"></i>
</div>


JQuery:

$("[id^=stars] > i").hover(function() {
count = $(this).attr("data-count");
$(this).each(function (i) {
if ($(this).attr("data-count") < count)
$(this).addClass("yellow");
});
console.log($(this));
});


But this only fills one single star to yellow. I need to select and fill all previous single
<i>
elements somehow. How can I achieve this?

Answer

Please check the Fiddle. Is this what were you looking for ?

$("#stars3 > i").hover(function() {
$(this).prevAll().addClass('yellow').removeClass('grey')
$(this).addClass('yellow').removeClass('grey')
$(this).nextAll().addClass('grey').removeClass('yellow')
});