How to go through the brother elements with jQuery?

Asked

Viewed 194 times

1

What I want to do is to pass the mouse over some star, all the previous ones including it was with a "selected" class, I tried to use siblings along with each and almost got the result where I wanted to.

The result I want to arrive at is something like this: inserir a descrição da imagem aqui JQUERY

$('.estrela').on({
    'mouseenter': function () {
        $(this).siblings().each(function () {
            $(this).removeClass("fa-star-o").addClass("fa-star");
        });
    }, 'mouseleave': function () {
        $(this).removeClass("fa-star").addClass("fa-star-o");
    }
});

HTML

<form>
    <h5>1 - Quantas estrelas você recomenda?</h5>
    <?php for ($i = 1; $i <= 5; $i++): ?>
     <a href="#" class="estrela fa fa-star-o" data-estrelas="<?= $i; ?>"></a>
    <?php endfor; ?>
 </form>

1 answer

1


Uses the event.target to know what the current element is, and always iterate the collection. Then with a return false; make the loop stop.

Suggestion:

var estrelas = $('.estrela');
estrelas.on({
  'mouseenter': function(e) {
    estrelas.each(function() {
      $(this).removeClass("fa-star-o").addClass("fa-star");
      if (this === e.target) return false;
    });
  },
  'mouseleave': function(e) {
    $(this).removeClass("fa-star").addClass("fa-star-o");
  }
});
a {
  text-decoration: none;
  color: #ECC202;
}
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="estrela fa fa-star-o"></a>
<a href="#" class="estrela fa fa-star-o"></a>
<a href="#" class="estrela fa fa-star-o"></a>
<a href="#" class="estrela fa fa-star-o"></a>
<a href="#" class="estrela fa fa-star-o"></a>

  • 1

    Thank you Sergio, that’s exactly what I wanted!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.