Move on hover, then remain in place when the mouse is clicked, revert to the original position when clicked once more

I want an image to rotate 180 degrees when hovered over. When the image is clicked, I want it to stay in that position until clicked again to return to its original position.

While I've tried using a combination of CSS for the hover effect, it doesn't persist. I came across some jQuery examples but found them too basic to understand how to make the image return to its original position when clicked again.

The HTML:

<div class="conversionFormE" id="switch1">
  <label class="swapHide">Swap?</label>
  <input type="button" class="rotate" id="switch" name="switch" value="" onclick="switchUnits()"/>
</div>

Some of the CSS:

.rotate {
  -webkit-transition-duration: 0.8s;
  -moz-transition-duration: 0.8s;
  -o-transition-duration: 0.8s;
  transition-duration: 0.8s;

  -webkit-transition-property: -webkit-transform;
  -moz-transition-property: -moz-transform;
  -o-transition-property: -o-transform;
  transition-property: transform;

  overflow:hidden;
}

.rotate:hover {
  -webkit-transform:rotate(180deg);
  -moz-transform:rotate(180deg);
  -o-transform:rotate(180deg);
}

Any help would be appreciated.

EDIT: Here's the onClick function as requested:

function switchUnits(){

//need to get values before swap to and from around.
var from = $("#from").val();
var to = $("#to").val();

//switches the details
$("#to #"+from).attr("selected","selected");
$("#from #"+to).attr("selected","selected");

//gets values after switch
from = $("#from").val();
to = $("#to").val();

//run convert
convertUnits();
}

EDIT: Is it possible for the image to rotate back to its original position on hover without needing to click it again? For example:

In Position A, hover, rotate, click, stay in Position B. In Position B, hover, rotate back, click, stay in Position A again.

Answer №1

To enhance your CSS styling, consider incorporating a selector like .rotate.rotated into your existing code for the .rotate:hover class. This method ensures that the specified styles will be applied when the additional class rotated is present.

To implement this functionality, you can use the following jQuery script to toggle the 'rotated' class upon clicking:

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

For a practical demonstration, refer to this example: http://jsfiddle.net/XHnD8/

Answer №2

If you want to make an element rotate on click and return to its original position on mouseout, try implementing the code below:

var clicked = 0;
$(".rotate").click(function () {
   clicked++;
   if (clicked == 1) {
       $(this).addClass("stay");
   }
}).bind("mouseout", function () {
    if (clicked == 2) {
        $(this).removeClass("stay").addClass('normal');
        clicked = 0;
    }
});

To style the rotation, use the following CSS:

.rotate:hover, .stay {
    -webkit-transform:rotate(180deg);
    -moz-transform:rotate(180deg);
    -o-transform:rotate(180deg);
}
.normal {
    -webkit-transform:rotate(0deg)!important;
    -moz-transform:rotate(0deg)!important;
    -o-transform:rotate(0deg)!important;
}

For a working example, check out: http://jsfiddle.net/ScSHm/

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

I am looking to modify various attributes linked to Rails

My Desire for Reality I am looking to update multiple related values in Rails by sending an update request from JavaScript. While creating data was seamless, I encountered difficulties when attempting to update it. #Code JavaScript* export const actions ...

Achieving Image Center Alignment in Bootstrap for Responsive Designs

My code snippet appears fine in full-width view, but when I resize the browser, the images (cards) are not centered and lean towards the left side. How can I correct this issue? This is the HTML code I am using: <div class="container-fluid"> ...

JavaScript formula for calculating dates together

I'm currently developing a PHP program for generating invoices. I'm implementing a datetimepicker to select the invoice generation date and due date. Now, I need the due date field to be automatically populated by adding a specific value to the i ...

Adjusting table column widths in Bootstrap 4

I am completely new to bootstrap and am in the process of enhancing an existing MVC web application that is already utilizing bootstrap 4. My goal is to incorporate a table with form fields, but I am facing difficulties in controlling the column widths of ...

Verify the presence of a CSS class within the stylesheet file using code-behind logic

In managing the styles for a series of pages, I have developed a common utility method. My goal is to determine if a CSS class exists in the .css file and then apply it, otherwise default to a standard style. For example, both PageA.aspx and PageB.aspx us ...

Preventing Shift: How to Only Replace the Chosen Vue Draggable Item Without Affecting Other Grid Items

Let's try an example to demonstrate: https://codesandbox.io/s/j4vn761455?file=/src/App.vue:112-116 Step 1: Drag item 4 to where 5 is. Notice how 4 and 5 switch positions. Step 2: Now, drag item 1 to position 6. Watch as 1 moves to where 6 was, pushi ...

Eliminating Google Adsense from Blog Posts

In each of my posts, I manually insert one Adsense unit. Here is the code: <div id="toppostad" style="float: left"> Adsense code </div> Initially, I assigned an id to the div when placing the code with the intention of using display:none; to ...

Creating dynamic input fields in a React component allows for a more interactive user

In my current project, I have a div section that includes three input fields and a remove button. The goal is to allow users to dynamically add this div when clicking on the "Add" button, and remove it when clicking on the "Remove" button. Initially, I man ...

What is the method to establish a fixed horizontal sizing for :before elements?

I am attempting to create a ul menu with a :before pseudo-element on li tags. The text inside the :before's content varies for each row. I am aiming to align this text to the right for each li, like so: pseudo_x li pseudo_xx li pseudo_xxx li li: ...

Using AngularJS to bind radio buttons to ng-model

Here is a snippet of my HTML code where I attempted to bind the "formFriendsAll" scope to the ng-model. <form ng-submit="submitForm()" > <div class="col-sm-3"> <div class="form-group"> <label>Which Persons to show?< ...

Uploading Large Files with Laravel 5.4: Utilizing Chunk Upload and Resumable Upload

Can anyone confirm if Laravel version 5.4 or newer has built-in support for chunked file uploads for large files, as well as resumable upload capabilities in case of network interruptions? I need to upload videos with large file sizes but have been facing ...

Unrestricted access to Fetch from Origin in Express.js is restricted by CORS policy

I'm trying to send data from a basic html form to an Express.js endpoint. However, when I attempt to post the data, I encounter the following error: "Access to fetch at 'https://samplesite.net/sample' from origin 'https://samplesi ...

d3 Error: Unable to retrieve the length property of an undefined value

I am currently working with a large JSON file in d3, approximately 75 KB in size. It seems to be functioning properly for the first 32 data objects, but then an error appears in the console stating 'Cannot read property 'length' of undefined ...

On the iPad, CSS styling will not be visible if an element's width exceeds 920 pixels

I recently developed a website optimized for monitors, but when I viewed it on an iPad, the right corner was missing some CSS styles. Take a look: Here is the HTML code: <div id="nav-top"> <div class="wrapper"> <!-- To ...

Achieving Integration of External SDK with Angular: A Guide to Updating DOM Post SDK Async Calls

Currently, I am developing a client-side JavaScript SDK that simplifies requests to an external API. However, there is one issue when using this SDK within Angular. Developers have to manually add $scope.apply() in order to update the DOM correctly. SDK. ...

Chrome displays linear-gradient with choppy rendering

I am attempting to enhance a page by adding a ribbon using CSS3 linear-gradients, but I have noticed that the way Chrome renders it is not as attractive as Firefox or IE. The color stops in Chrome appear pixelated, and unfortunately using vendor prefixed p ...

Is there a way I can implement jQuery animation on my pop-up window?

I've successfully set up a basic popup using jQuery. When a button is clicked, it changes the 'display' property of a div from 'none' to 'block' in CSS and creates an overlay to darken the background. Take a look at my c ...

Tips for displaying a navbar dropdown menu outside of its container

Before encountering this issue, I was struggling with making the navbar scroll on smaller screens when expanded. I found a helpful solution on Stack Overflow: responsive fixed-top navbar when expanded fills up screen, hides some of the nav-links, and does ...

Navigating to a dynamically inserted element within a React component

I've implemented this code that I trigger on a button click to smoothly scroll to the bottom of a page: const el = useRef<HTMLDivElement>(null); const ScrollToBottom = () => { if (el.current !== null) el!.current!.scrollIntoView ...

Tips for utilizing this RegEx in my PHP code to maintain UTF-8 characters while eliminating symbols

I am striving to eliminate symbol characters such as #$^&%()'"!,.? and whitespace from my string, while keeping all other UTF-8 characters, numbers, and regular characters intact. I have successfully implemented this on the front-end using JavaScr ...