Search code examples
jqueryfont-awesome-5

Jquery attribute change after hover of Fontawesome Pro only work once


Trying to create a simple rating system on hover with Fontawesome Pro. Basically when hover should show solid stars on all previous icons and light on all next.

<div id="ratings" class="panel-body">
  <h1>Ratings</h1>
  <i class="fal fa-star fa-2x" aria-hidden="true"></i>
  <i class="fal fa-star fa-2x" aria-hidden="true"></i>
  <i class="fal fa-star fa-2x" aria-hidden="true"></i>
  <i class="fal fa-star fa-2x" aria-hidden="true"></i>
  <i class="fal fa-star fa-2x" aria-hidden="true"></i>
</div>

and jquery is:

$(document).ready(function() {
    $("#ratings svg").hover(function() {
      var $this = $(this);
      $this.nextAll().attr('data-prefix','fal');
      $this.prevUntil("h1").attr('data-prefix','fas');
      $this.attr('data-prefix','fas');
    });
});

It works once and stop right after first change. Also tried removing attr before, but still no luck.

$(document).ready(function() {
    $("#ratings svg").hover(function() {
      var $this = $(this);
      $this.nextAll().removeAttr('data-prefix','fas').attr('data-prefix','fal');
      $this.prevUntil("h1").removeAttr('data-prefix','fal').attr('data-prefix','fas');
      $this.removeAttr('data-prefix','fal').attr('data-prefix','fas');
    });
});

Solution

  • With Fontawesome Pro, you have to put the <i> inside a span

    <div id="ratings" class="panel-body">
      <h1>Ratings</h1>
      <span><i class="fal fa-star fa-2x" aria-hidden="true"></i></span>
      <span><i class="fal fa-star fa-2x" aria-hidden="true"></i></span>
      <span><i class="fal fa-star fa-2x" aria-hidden="true"></i></span>
      <span><i class="fal fa-star fa-2x" aria-hidden="true"></i></span>
      <span><i class="fal fa-star fa-2x" aria-hidden="true"></i></span>
    </div>
    

    and target the svg inside the span

    $("#ratings span").hover(function () {
        var $this = $(this);
        $this.nextAll().find('svg').attr('data-prefix','fal');
        $this.prevUntil("h1").find('svg').attr('data-prefix','fas');
        $this.find('svg').attr('data-prefix','fas');
    });