Rotate icon "Arrow" with JS

3

This question may seem simple, but I can not find a quality answer. I have an arrow icon and when I click on it, I want it to turn 180 degrees. The code I started using was this:

$('.arrow').click(function() {
      $('.rodar').toggleClass('rodado');
  });
.rodado{
     transform:rotate(180deg);
     transition: all 0.3s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkhref="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<i class="material-icons dots green arrow rodar">keyboard_arrow_down</i>
<br>
<i class="material-icons dots green arrow rodar">keyboard_arrow_down</i>

But as you can see in the example, if I click on one, the two run. this does not work. Can you do it somehow?

    
asked by anonymous 21.09.2018 / 15:43

2 answers

3

Note that in this row you are applying the effect on all elements that have the class rodar :

$('.rodar').toggleClass('rodado');

To get only the element that was clicked, use $(this).

$('.arrow').click(function() {
      $(this).toggleClass('rodado');
  });
.rodado{
     transform:rotate(180deg);
     transition: all 0.3s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkhref="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<i class="material-icons dots green arrow rodar">keyboard_arrow_down</i>
<br>
<i class="material-icons dots green arrow rodar">keyboard_arrow_down</i>
    
21.09.2018 / 15:52
3

The method jQuery.toggleClass belongs only to the jQuery library, the Element.classList.toggle would be the native JS equivalent.

Then, you either convert this to a jQuery object using the code:

$(this).toggleClass("rodado");

Or you use the native element using:

this.classList.toggle("rodado");

Just check Browser Compatibility .

$('.arrow').click(function() {
    $(this).toggleClass('rodado');
    // ou
    // this.classList.toggle('rodado')
});
.rodado{
     transform:rotate(180deg);
     transition: all 0.3s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkhref="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<i class="material-icons dots green arrow rodar">keyboard_arrow_down</i>
<br>
<i class="material-icons dots green arrow rodar">keyboard_arrow_down</i>
    
21.09.2018 / 15:55