Spinning divs using JavaScript when the mouse hovers over them, and then returning them to their original position when the mouse moves

I am looking to create a functionality where a div rotates when the mouse enters it and returns to its original position when the mouse leaves. Everything works fine when interacting with one div, but as soon as I try hovering over other divs, it starts glitching.

Here is the JavaScript code:


$(document).ready(function(){

var blocks = document.getElementsByClassName('block-item');

for (var i = 0, max = blocks.length; i < max; i ++) {
    blocks[i].onmouseenter = blocks[i].onmouseleave = handler;
}

var startRotate = function(blackFrame, blackFrameAngle) {
// ...
};

var startRotateBack = function(blackFrame, blackFrameAngle) {
// ...
};

function handler(event) {

  // If mouse enters start rotating clock-wise
  if (event.type == 'mouseenter') {

        // Calculate angles
        var blackFrame = event.target.querySelectorAll('.block-frame')[0];
        var blackFramePos = getComputedStyle(blackFrame).getPropertyValue('transform');
        var blackFrameValues = blackFramePos.split('(')[1],
            blackFrameValues = blackFrameValues.split(')')[0],
            blackFrameValues = blackFrameValues.split(',');
        var a = blackFrameValues[0];
        var b = blackFrameValues[1];
        var radians = Math.atan2(b, a);
        if ( radians < 0 ) {
            radians += (2 * Math.PI);
        }
        var blackFrameAngle = Math.round( radians * (180/Math.PI));

    // Start rotating
    startRotate(blackFrame, blackFrameAngle);

  }

  // If mouse leaves stop rotating clock-wise and start rotating back
  if (event.type == 'mouseleave') {

    clearInterval(RotateFrame)
    // ...
    // ...
    // Start rotating back
    startRotateBack(blackFrame, blackFrameAngle);

  }

}

});

You can find the full code in this jsfiddle http://jsfiddle.net/fw3ma9ej/2/

Answer №1

To achieve the desired effect, we can utilize the CSS transition property and modify the rotation angle of the element when it is hovered over.

For a visual representation, you can refer to this example: http://jsfiddle.net/j10y98w2/1/

transform: rotate(45deg);
transition: transform 5s ease-out;
&:hover {
  transform: rotate(315deg);
}

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

Overflowing content in a table within a div element

Issue: I am encountering a problem with resizing a table inside a div that contains input elements. When I adjust the browser window size or change to a lower resolution, the div element resizes and scales down, causing a horizontal scroll bar to appear. H ...

Inspect all checkboxes created by JavaScript

I'm attempting to develop a checkall checkbox that will automatically select all the checkboxes I've created using JavaScript. Firstly, I gather the number of rows and columns from the user and then use JavaScript to generate a table and insert ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Designing a toggle button interface with Material UI

Looking to add a toggle button to my page. Here is an image of what I have in mind: https://i.sstatic.net/tiQAP.png Unable to find any material-ui component or API for this specific toggle button design. Considering building a custom toggle button with CS ...

Using CSS to create hover effects for specific classes of elements

Is there a way to make the button change color on hover when hovering over anywhere in the navigation bar (.topNav) instead of just when hovering over the individual button elements (.top, .middle, .bottom classes)? I tried using span to achieve this, but ...

Comparing defaultProps with the logical OR operator

Being relatively new to react, I’ve adopted a method of defining default values which looks like this: class TextInput extends Component { render() { return ( <input type="text" name={ this.pr ...

Using ngTable within an AngularJS application

While working on my angularjs application, I encountered an issue with ngtable during the grunt build process. It seems that the references are missing, resulting in the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module pa ...

Using a jQuery AJAX anonymous function to send form data

I'm attempting to send an Input file field using jQuery Ajax, but I keep encountering an anonymous function error in my Chrome inspector console. The issue seems to be related to this line in my script: Here's the code snippet I execute after en ...

I am encountering issues with my JavaScript files that appear to be following the correct path, however they are not functioning properly. Error messages such as SyntaxError: expected expression

I am currently working on a Yii2 application. My goal is to utilize the JavaScript and CSS files from the common folder in my backend. The paths for these files are within the common/web/js and common/web/css directories respectively. To achieve this, I ...

Optimizing website layout for mobile devices

I have a website with a fixed page layout at . It displays properly on desktop browsers but not on mobile devices. The website is adjusting to fit the browser size, but some components are changing format. Can anyone offer assistance? Thank you! ...

Troubleshooting Problem with Displaying SVG Images

Snippet for Header Component import React from 'react' const Header = () => { return ( <div> {/* Main-header */} <header className=''> {/* Header-background */} {/* <div c ...

Collecting all Material-UI components into a single document

Currently, I am engaged in a Meteor project that utilizes Material UI and ReactJS. I wish to streamline the process by creating a single file that imports all necessary Material UI components for my project. This way, instead of adding individual exports ...

Updating a Django div with JQuery and AJAX

Looking for a way to refresh a specific part of my page using AJAX and JQuery in Django. How can I ensure that only the div is updated, rather than the entire page? // Code snippet from my template var tag_cloud_floor = function(floor) { $.ajax({ ...

centering the text within the div for perfect alignment

I've been attempting to customize a Register form. My goal is to position the heading in the center of the div while having another login form located right beside it. Using flexbox, I styled them and then applied justify-content as center. Additiona ...

Encountering a 404 error while sending a session ID in a Post request using AngularJS

My services are hosted on a remote server, and I am consuming these services in a local AngularJS app. Everything works fine with REST requests that do not require a SessionID in the header. However, when I add the Session ID in the header, it does not wor ...

Is it possible to create an index.html page with all the necessary head tags to prevent duplicate code across multiple html pages?

Imagine I am using app.js or a Bootstrap CDN link for all of my HTML pages, but I don't want to include it in every single page individually. Is there a way to create an index.html file that includes this so that all other HTML pages load the head fro ...

Steps for Loading HTML5 Video Element in Ionic 2

Struggling to showcase a list of videos from my server, here's the issue I'm encountering and the layout of the app. https://i.stack.imgur.com/HWVt3.png This is the code snippet in HTML: <ion-list> <button ion-item *ngFor="let v ...

Enhancing Watermark Functionality for Text Boxes

I am encountering an issue with three textboxes all having watermarks. When I use JavaScript to set the value of the second textbox in the OnChange event of the first textbox, the text appears as a watermark. However, when I click on the textbox, it become ...

Tips for including a DOCTYPE declaration when generating an XML document with the "xmlbuilder" npm library

Is it possible to include a !DOCTYPE declaration in an XML file while using the 'xmlbuilder' package? I want to add something similar to the following: <!DOCTYPE IAD.IF.ESTATE.FORRENT SYSTEM "http://www.finn.no/dtd/IADIF-estateforrent71.dtd" ...

Struggling to securely post data to an Express server by hashing passwords with bcrypt?

I'm currently working on developing an API using Express and Sequelize. Specifically, I am writing a function to create a new user where I utilize bcrypt for password hashing. const createNewUser = (data) => { return new Promise(async (resolve, ...