What is the best way to rotate a square in both clockwise and counterclockwise directions when the

When the mouse hovers over, the square will rotate in a clockwise direction for odd-numbered hover events and in an anticlockwise direction for even-numbered hover events.

var box = document.getElementById("box")

function rotate() {
  //if ( ? ? ? ) {
  //  box.className = 'even';
  //} else {
  //  box.className = 'odd';
  //}
}
#box {
  width: 100px;
  height: 100px;
  background: red;
  transition: transform 1s;
}

.even {
  transform: rotate( -180deg);
  /* transition: transform 150ms ease; */
}

.odd {
  transform: rotate( 180deg);
  /* transition: transform 150ms ease; */
}
<div id="box" onmouseover="rotate()"></div>

Answer №1

If you require it, I am able to achieve this using only CSS. Here is the code snippet:

.cmn {
  display: inline-block;
  padding: 65px;
  background: red;
  margin: 45px;
  color: #fff;
}

.even {
  transform: rotate(0deg);
  transition: transform 150ms ease; 
}
.even:hover {
  transform: rotate(-180deg);
  transition: transform 150ms ease; 
}

.odd {
  transform: rotate(0deg);
  transition: transform 150ms ease; 
}
.odd:hover {
  transform: rotate(180deg);
  transition: transform 150ms ease;
}
<div class="cmn even">Lorem Even</div>
<div class="cmn odd">Epsum Odd</div>

Answer №2

Utilize pure CSS as demonstrated in the code snippet below Have you considered using even and odd selectors without any corresponding HTML elements? There is no requirement for JavaScript to achieve element rotation.

#box {
width: 100px;
height: 100px;
background: red;
transition: transform 1s;
}

#box:hover { /* modification occurs here */
    transform: rotate( -180deg );            
    /* transition: transform 150ms ease; */
}

#box:hover { /* another modification */
    transform: rotate( 180deg );            
    /* transition: transform 150ms ease; */
}
<div id="box"></div>

Answer №3

let container = document.getElementById('container');
let isRed = true;

function changeColor(){
    if(isRed === true){
        container.className = "red";
    } else{
        container.className = "blue";
    }
    isRed = !isRed;
}

#container {
    width: 150px;
    height: 150px;
    background-color: red;
    transition: background-color 1s;
}
.red{
    background-color: red;
} 
.blue{
    background-color: blue;
}

<div onmouseover="changeColor()" id="container"></div>

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

Display HTML code inside a specified div

I am attempting to incorporate content from another HTML file into my current web page using jQuery's .load method. Unfortunately, the content is not loading as expected. Can anyone provide me with a solution to this issue? Below is the HTML and jQ ...

Performing addition and multiplication operations on separate identifiers with the help of Jquery

Currently, I am working on developing a shopping cart website and I am new to using Jquery. My layout involves the need to increment and decrement values by one when the plus and minus button is pressed. Additionally, the total price value should also be a ...

Is it possible to enable extensions in incognito mode as the default setting?

After creating a chrome extension, I am now looking to have it automatically work in incognito mode. Despite my efforts to find a solution, I haven't come across anything helpful yet. During my search, I came across mentions of the selenium web driver ...

Retrieving the value of a field using its name within a Meteor template

I have two variables in my template rows and fields storing the documents and field names in the collection, respectively. I display it using {{#each rows}} <tr> {{#each fields}} <td>{{name}}</td> {{/each}} </tr> ...

Issue with October CMS: Radio button selection triggers an Ajax call, but clicking twice in quick succession causes the content

I am currently utilizing October CMS and materializecss to develop a form with options on one of my pages. The form functions correctly as it dynamically loads content when different options are clicked. However, I have identified a problem where clicking ...

Execute a function only after the completion of another

I am trying to implement a function where the .hidden class is added to a div only when it has scrolled to the top. I know I can use SetTimeout, but I want to ensure that the div disappears only when it has reached the top of the scroll. $(".more").on(" ...

Creating a query string in MongoDB using [Object] as a field

Currently, I am in the process of constructing a string within Meteor to delve deeper into my MongoDB data. The structure of my data can be seen here: Data In my JavaScript code for Meteor projects, I have formulated the string as shown below: const co ...

Tips for refreshing React context after a successful login

After a successful login by the user, I expect to receive a response code of 200 from the server. At this point, my aim is to update the variable within my ReactContext Provider. However, I encounter a challenge because I can access the toggleAuth function ...

What is the method for verifying a condition within a Javascript function?

Recently delving into Javascript, I have encountered a situation with a JS method. It seems that most of the time, both the SSID and SecurityMode are the same in the lists of wifi networks I receive. I would like to filter out instances where both SSID and ...

Utilizing Z-Index on DropDownTree has no impact on its display

Whenever the DropDownTree is placed near other expanding controls such as standard date pickers, it causes those controls to appear behind the DropDownTree. I have attempted various solutions including using inline style, setting z-index for .RadDropDownTr ...

Using elements and querySelector in VueJS is not effective

After successfully creating HTML elements using JavaScript, I attempted to convert the code into VueJS. However, upon loading the page, I noticed that the elements were not being created. HTML <div id="chat" class="chat-size col-centered margin-btm-50 ...

Steps for handling errors in Node.js when the query result rowCount is 0 and throwing an error in response

If the rowcount is 0, I need to send a response as failed. If the rowcount is 1, I need to send a success status. Can someone please assist me with this? When I try to print (client.query), it displays the result in JSON format (refer to attached image). ...

Testing Async operations in the browser with Mocha and Chai

I'm having trouble running async tests with mocha. Below is the snippet of my code: describe('Brightcove Wrapper',function(){ describe("#init()", function() { it("Should inject the brightcove javascript", function(callback){ ...

Executing PHP Functions with Script Tags

I am trying to use PHP to output the <script></script> tag. Here is the code I am using: <?php echo "test"; echo "<br>"; echo '<script src="http://mywwebiste./mycode.js" type="text/javascript& ...

How to conditionally close a <div> tag in Vue.js

My API is returning chat messages in a specific object format. messages : [ [ sender: "John Doe", text: "Some message", sent_at: "2020-09-26", date_group: "Today", ], [ ...

I'm having trouble obtaining accurate results for $....<...$ within the <li> tags using MathJax

I have gained extensive experience working with LaTeX formatting, but not every document follows the standard practice of having a space before and after the symbols < and >. When I attempt to use MathJax to display these documents, they fail to rend ...

Creating a dynamic two-player chess application using Django - requiring the player's chess board to automatically update whenever the opponent makes a move

I am looking for a solution where each player has their own webpage equipped with a Javascript chessboard GUI interface that allows them to click and drag pieces. The challenge is ensuring that when one player makes a move, the other player's chessboa ...

Enhance the current menu item in WordPress by assigning a class to the anchor tag

function updateActiveClassOnMenu($item_output, $item, $depth, $args) { $menu_locations = get_nav_menu_locations(); if ($item->menu_order == 1){ $item_output = preg_replace('/<a /', '<a class="active" ', $item_o ...

Call a function of a javascript object from inside a callback function

In a user script, I have defined the MyClass and its methods as follows: function MyClass() { this.myCallback = function() { alert("MyClass.myCallback()"); }; this.startRequest = function() { GM_xmlhttpRequest({ &a ...

Securing Objects in Parse with the JavaScript API - Linking Users to their saved entities

When managing entities in Parse, I often need to associate various objects with the user currently logged in. My main concerns are: There is no backend code in place to ensure that the User being passed in is actually the logged-in user. Users could poten ...