Run icon "Arrow" with JS

Asked

Viewed 53 times

3

This may sound simple, but I can’t find a good answer. I have an arrow icon and when I click 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>
<link href="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 turn. The this does not work. It has to do it somehow?

2 answers

3


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

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

To catch only the element that was clicked, use the $(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>
<link href="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>

  • Thanks! Strange is that I tried to use this, but it didn’t work... it must have been some cache problem, now it worked fine, thanks!

  • Or did you use this instead of turning it into a jquery object, like this $(this)

  • You were faster. hahaha

  • @fernandosavio your answer was also well prepared. + 1

3

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

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

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

Or you use the native element using:

this.classList.toggle("rodado");

Just check the 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>
<link href="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>

Browser other questions tagged

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