Sayuj3 Sayuj3 - 11 days ago 5
CSS Question

Glyphicon not spinning when clicked

I am working on a script which spins the icon class="glyphicon glyphicon-star" when clicked.

Here is the css code

.glyphicon-star-animate {
-webkit-animation-name: rotateThis;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
}

@-webkit-keyframes "rotateThis" {
from {
-webkit-transform: rotate( 0deg );
}
to {
-webkit-transform: rotate( 360deg );
}
}


Here is the jquery code :

$( document ).ready( function() {
$( "#update" ).on( "click", function( e ) {
var $icon = $( this ).find( ".glyphicon.glyphicon-star" ),
animateClass = "glyphicon-star-animate";

$icon.addClass( animateClass );
// setTimeout is to indicate some async operation
window.setTimeout( function() {
$icon.removeClass( animateClass );
}, 2000 );
});

});


Here is the HTML Code :

<a id="update" href="#"><i class="glyphicon glyphicon-star"></i></a>


My project consists of displaying several divs(extraction from db using php's fetcharray loop function)with different contents inside it.
But the glyphicon glyphicon-star i use is same in every div i could see. My problem is the rotating function or the jquery run only on the first div. The second div or the succeeding class="glyphicon glyphicon-star" is not rotating on click independently. How can i make them rotate independently ?

Answer

You need to make the ID update to class. Coz ID is unique identifier. you can use only one id for one element. LiveOnFiddle

 $(document).ready(function() {
  $(".update").on("click", function(e) {
    var $icon = $(this).find(".glyphicon.glyphicon-star"),
      animateClass = "glyphicon-star-animate";

    $icon.addClass(animateClass);
    // setTimeout is to indicate some async operation
    window.setTimeout(function() {
      $icon.removeClass(animateClass);
    }, 2000);
  });

});
 .glyphicon-star-animate {
 -webkit-animation-name: rotateThis;
 -webkit-animation-duration: 2s;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-timing-function: linear;
   }

  @-webkit-keyframes "rotateThis" {
  from { 
    -webkit-transform: rotate( 0deg );  
   }
 to  { 
    -webkit-transform: rotate( 360deg ); 
   }
  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<div>
<a class="update" href="#"><i class="glyphicon glyphicon-star"></i></a>
</div>
<div>

  <a class="update" href="#"><i class="glyphicon glyphicon-star"></i></a>
</div>
<div>

  <a class="update" href="#"><i class="glyphicon glyphicon-star"></i></a>
</div>

Comments