While attempting to change the color of 1 to 5 elements on mouse hover based on the data-rating tag, I am encountering a few issues. The data is retrieved correctly, but there are some problems:
- The function is being called 5 times each time there is a hover, instead of just once.
- All elements receive the color upon mouse enter, then all 5 colors are removed upon mouse leave.
- I believe there must be a more efficient way to achieve this, especially in the loop section. I aim to keep it DRY (Don't Repeat Yourself) here, and the current method definitely does not adhere to that principle.
The HTML code snippet:
<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 part:
$('[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');
}
});
Check out the fiddle here: fiddle