Click to trigger image rotation with JavaScript

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 attempting to create a rotating image effect on click. Although I followed a tutorial that seemed to work for someone else (http://jsbin.com/bukacesari/edit?html,css,js,output), it's not functioning as expected for me. Can you help me understand why it's not working and how I can fix it? I feel like I must be missing something simple, but I can't figure out what's wrong. Thank you!

Answer №1

To ensure that the document is fully loaded before attaching a click event, you can utilize one of these methods:

1- Embrace the jQuery ready event:

$(document).ready(function() {
    //DOM is fully loaded. You can safely attach events here.
});

You also have the option to use this shortcut:

$(function() {
    //DOM is fully loaded. You can securely attach events here.
});

2- Place your script just before the closing </body> tag:

<body>
    <!-- Your HTML content goes here -->
    <script>
        //Manipulate the page confidently in this area!
    </script>
</body>

Example showing the usage of $(function() {....}):

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experience a dynamic D3 geometric zoom effect when there is no SVG element directly underneath the cursor

Currently, I am working on incorporating a geometric zoom feature into my project. You can see an example of what I'm trying to achieve in this demo. One issue I've encountered is that when the cursor hovers over a white area outside of the gree ...

Opera's compatibility with jQuery's Append method allows developers to

I recently wrote a jQuery script that interacts with a JSON feed and dynamically creates HTML code which is then added to a designated div on my WordPress site. Surprisingly, the functionality works flawlessly in all browsers except for Opera - where not ...

Steps for assigning an id to an element using Selenium

When using Selenium, you have the ability to access the underlying DOM of the browser being manipulated through IWebElement instances. For example: IWebElement domWrapper = driver.FindElement(By.Name("q")); But what if you have the "domWrapper" instance ...

Verify if the JSON response contains any data

When the JSON response is empty and viewed in the browser console, it appears like this: {"data":{},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://url/form/BN217473" ...

Denied rendering of design due to incompatible MIME type

Just delved into the world of node / express and decided to test my skills by creating a simple tip calculator app. However, I seem to have hit a roadblock with loading my CSS. The console keeps throwing this error: "Refused to apply style from &apos ...

Referencing a variable within a string: Discord.js Hyperlink

Essentially, when attempting to use a discord hyperlink, I found that breaking the string to add a variable does not work as expected. I have tried calling it using $ and {} but it still doesn't work. .addField('Shortcuts', $'[Profil ...

Return the information from Node.js to the JavaScript on the client side

My goal is to establish a fetch connection from client-side JS to the server Node.JS. When a person clicks on a button in HTML, it triggers a search in the MongoDB database on the server side. Once the element is found, I am unsure how to send that informa ...

Executing multiple HTTP requests simultaneously in groups using an asynchronous for loop for each individual request

I'm currently working on running multiple requests simultaneously in batches to an API using an array of keywords. Read Denis Fatkhudinov's article for more insights. The issue I'm facing involves rerunning the request for each keyword with ...

Tips for swapping out an item mid-scrolling?

What is the best way to change the navbar when scrolling a page in React? How can I achieve this while following React's concepts? Is using getElementById considered bad practice? const useState = React.useState const useEffect = React.useEffect con ...

String object causing jQuery selector to malfunction

const newHTML = '<html><head><title>Hello</title><link rel="apple-icon-touch-precomposed" href="image.jpg" /></head><body></body></html>'; alert($(newHTML).find('link[rel="apple-icon-touc ...

Tips for embedding 2 rows within a <td> element in a DataTables table

Here's a unique layout I want to achieve using the DataTables plugin. https://i.sstatic.net/YxfOk.png Notice how the address spans across 3 columns. This html code disrupts the sorting feature of DataTables and causes the table to shift. Here&apos ...

Difficulty in implementing jQuery accordion height style using either content or fill option

What I am looking for is to have only one specific div in my accordion (device properties) change its height based on the content. I have also noticed that if I use Firebug to remove the height property of the device div, it adjusts the height correctly. ...

Using Angular to swap out the component's selector with HTML code

Consider the following component: @Component({ selector: 'passport-cell', templateUrl: './passport-cell.component.html', styleUrls: ['./passport-cell.component.scss'] }) export class PassportCell { @Input() public la ...

Resizing rectangular images with CSS/Bootstrap into perfect squares

Imagine there is a rectangular image with dimensions of 1400px (height) x 700px (width). I am looking to turn it into a square while maintaining its original proportions and having white sides added. I specifically do not want to crop the image - I want it ...

Deciphering the intricacies of Bootstrap 4's navigation

Embarking on a new journey in web development, I am currently enrolled in a webdev course and diving into the world of CSS through Bootstrap. While the instructional videos were based on Bootstrap 3, I am determined to master Bootstrap 4. Currently, I am g ...

Issue with the pluses and minuses in the Bootstrap accordion

Can someone explain why the panel-header displays all "-" instead of "+"? When I click on the panel, it changes all "-" to "+". This happens consistently, not just the first time the page loads. My CSS code: .panel-heading a:after { font-family: &ap ...

Updating multiple subdocuments with Mongoose

My goal is to update a specific subdocument called addresses (which is working fine) and then update all other subdocuments except the one that was just changed. Whenever an address is changed to have is_preferred set to true, I need to update the previous ...

What's the best choice: Fixed or Variable Column Widths in Tables or Floats?

I'm currently working on a layout for a 3 column, full-width page. I want two columns to have a fixed width, while the third column should adapt to the full width between them, like this: | Fixed Width || Variable Width || Fixed Width ...

What is the best method to design a navigation bar that is responsive to different screen

I'm facing a challenge with making my website responsive. I've successfully made all the pages responsive, but I'm struggling to finalize the navigation part. You can view my website at www.christierichards.co.uk/gcc_website/index.php When ...

Tips for enabling only a single div to expand when the "read more" button is clicked

I'm having trouble with my blog-style page where I want only one "read more" link to expand while collapsing the others. I've tried various jQuery methods and HTML structures, but haven't been able to achieve the desired result. Can someone ...