0

I'm making a loop that returns several items, I have a Favorite button that when hover it runs a toggleClass to change the icon, but it only does that in the first item of the loop, can someone help me ?

<div class="favoriteButton" id="favoriteButton"> 
<i id="favoriteIcon" class="far fa-2x fa-heart"></i>
</div>

jQuery code:

// Favorite Icon
$("#favoriteIcon").hover(() => {
    $("#favoriteIcon").toggleClass("far fas"); 
});

Loop:

for ($i = 0; $i < count($vehicles); $i++) { 
  echo '<div class="favoriteButton" id="favoriteButton"> 
        <i id="favoriteIcon" class="far fa-2x fa-heart"></i>
        </div>';
}
bassxzero
  • 4,838
  • 22
  • 34

1 Answers1

0

Your for loop generate i elements which all have the same id favoriteIcon , in an html page it is incorrect for different elements to have the same id;

It would be correct to change your code to use classes instead like

for ($i = 0; $i < count($vehicles); $i++) { 
  echo '<div class="favoriteButton" > 
        <i class="far fa-2x fa-heart fav-icon-class"></i>
        </div>';
}

and you javascript to :

// Favorite Icon
$(".fav-icon-class").hover(function() {
    $(this).toggleClass("far fas"); 
});
ZIASH
  • 135
  • 5
  • 1
    $ (This) ... returns this to me: `Window {window: Window, self: Window, document: document, name: "", location: Location,…}` and if I don't pass $(this) but the class name as $(". fav-icon-class")... it changes all the icons in the loop @bassxzero – Gustavo Mello Jan 05 '21 at 14:10
  • Change `() =>` for `function()`. The [arrow Fuction Expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) has some limitations... Like it has no binding for `this`. – Louys Patrice Bessette Jan 05 '21 at 16:33