Lukáš Jirůšek Lukáš Jirůšek - 4 months ago 21
HTML Question

Rotate image using JavaScript after click



img {
display: block;
margin: 20px;
width: 50px;
height: 50px;
}

.crossRotate {
-webkit-transition-duration: 1s;
-moz-transition-duration: 1s;
-o-transition-duration: 1s;
transition-duration: 1s;
-webkit-transition-property: -webkit-transform;
-moz-transition-property: -moz-transform;
-o-transition-property: -o-transform;
transition-property: transform;
outline: 0;
}

.crossRotate.active {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$('.crossRotate').on('click', function(){
$(this).toggleClass('active');
});
</script>
<link rel="stylesheet" href="StyleSheet.css">
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<img class="crossRotate" src="https://s31.postimg.org/cf0ip4gd7/logo.gif" alt="Cross Menu button" tabindex="1" />
</body>
</html>





Hello, I am trying to make this image rotate 180 degrees after click. I copied almost everything from here: http://jsbin.com/bukacesari/edit?html,css,js,output , but it still doesn't work for me. Can you explain me why and how could I fix this ? This may be silly question, but I have no clue why it doesn!t work. Thanks

Answer

You need to wait for the page to be fully loaded in order to attach a click event:

img {
  display: block;
  margin: 20px;
  width: 50px;
  height: 50px;
}
.crossRotate {
  -webkit-transition-duration: 1s;
  -moz-transition-duration: 1s;
  -o-transition-duration: 1s;
  transition-duration: 1s;
  -webkit-transition-property: -webkit-transform;
  -moz-transition-property: -moz-transform;
  -o-transition-property: -o-transform;
  transition-property: transform;
  outline: 0;
}
.crossRotate.active {
  -webkit-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  transform: rotate(180deg);
}
<!DOCTYPE html>
<html>

<head>
  <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
  <link rel="stylesheet" href="StyleSheet.css">
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script>
    $(function() {
      $('.crossRotate').on('click', function() {
        $(this).toggleClass('active');
      });
    });
  </script>
</head>

<body>
  <img class="crossRotate" src="https://s31.postimg.org/cf0ip4gd7/logo.gif" alt="Cross Menu button" tabindex="1" />
</body>

</html>