I'm trying to color between 1 and 5 elements on mouse hover, based on data-rating tag. I get the data correctly, but several things happen:
- The function is accessed 5 times on each hover, instead of a single access.
- All of the elements gets the color on mouse enter, then all 5 gets cleared on mouse leave.
- I can feel there is a much more concise way of doing it, particularly in the loop section. I'm trying to keep it DRY here, and this ain't DRY for sure.
The HTML portion
<h2>
<i class="far fa-star" data-rating="1">1</i>
<i class="far fa-star" data-rating="2">2</i>
<i class="far fa-star" data-rating="3">3</i>
<i class="far fa-star" data-rating="4">4</i>
<i class="far fa-star" data-rating="5">5</i>
</h2>
The jQuery portion:
$('[class="far fa-star"]').mouseenter(function() {
var target = parseInt($(this).data('rating'));
for (i = 0; i < target; i++) {
$(this).parent().children(i).css('background-color', 'yellow');
}
});
$('[class="far fa-star"]').mouseleave(function() {
var target = parseInt($(this).data('rating'));
for (i = 4; i > target; i--) {
$(this).parent().children(i).css('background-color', 'transparent');
}
});
fiddle is here - fiddle