Home > Blockchain >  How to toggle between classes using jquery
How to toggle between classes using jquery

Time:04-04

I have a rating star in my page, and I'm trying to toggle back and forth between "fa fa-star" class and "fa fa-star checked" class I have read about this here: Javascript/Jquery to change class onclick? And this is my implementation (it didn't work)

$('.fa fa-star').click(function() { $(this).toggleClass('fa fa-star'); $(this).toggleClass('fa fa-star checked'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <span onclick="rating" ></span>
    <span onclick="rating" ></span>
    <span onclick="rating" ></span>
    <span onclick="rating" ></span>
    <span onclick="rating" ></span>
</div>

CodePudding user response:

You simply need to toggle the checked class for a simplified rating.

$('.stars i').click(function() {

  $('.stars i.checked').removeClass('checked');
  for (let i = 0; i < $(this).index()   2; i  ) {

      $('.stars i:nth-of-type('   i   ')').addClass('checked');

  }

});
.stars i {
  color: #ccc;
  cursor: pointer;
}

.stars i.checked {
  color: #dfd022;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div >
  <i ></i>
  <i ></i>
  <i ></i>
  <i ></i>
  <i ></i>
</div>

CodePudding user response:

maybe that...

document.querySelectorAll('i.fa-star')
.forEach( (star,indx,arr) =>
  {
  star.onclick =_=> 
    {
    let chk = star.classList.toggle('checked')
    arr.forEach((s,i) =>
      s.classList.toggle('checked', i<indx ? true: i===indx ? chk : false))
    }
  })
body {
  background : darkslategrey;
  font-size  : 24px;
  }
i.fa-solid.fa-star {
  color  : lightgray;
  cursor : pointer;
  }
i.fa-solid.fa-star.checked {
  color  : gold;
  }
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" />

<div>
  <i ></i>
  <i ></i>
  <i ></i>
  <i ></i>
  <i ></i>
</div>

  • Related