Enhancing animation with mouse movement in css [tips for improvement]

Greetings

As I delved into creating a function that would cause a particular behavior (the closer you move the mouse to a div, the closer the div moves to the mouse position on the parent's X axis, with a maximum div position of left:-40% and a minimum of left:-80%):

Important: The black arrow symbolizes the cursor (mouse position).

Code Snippet

HTML markup:

<div class="wraper">
    <div class="ls">
        <div class="ldiv">
        </div>
    </div>
    <div class="c">
        <div class="coordinates">
        </div>
        <div class="cdiv">
        </div>
    </div>
    <div class="rs">
        <div class="rdiv">
        </div>
    </div>
</div>

CSS markup:

body{
    margin: 0;
    padding: 0;
}
.wraper{
    width: 100%;
    height: 500px;
}
.ls, .rs{
    position: relative;
    float: left;
    width: 30%;
    height: 100%;
    background-color: #eeeeee;
}
.c{
    position: relative;
    float: left;
    width: 40%;
    height: 100%;
    background-color: #dddddd;
}
.cdiv{
    position: absolute;
    top: 25%;
    left: 10%;
    width: 80%;
    height: 50%;
    background-color: red;
}

.ldiv{
    position: absolute;
    top: 30%;
    left: -80%;
    width: 80%;
    height: 40%;
    background-color: red;
}
.rdiv{
    position: absolute;
    top: 30%;
    right: -40%;
    width: 80%;
    height: 40%;
    background-color: red;
}

Javacsript markup:

//Assigning global variables
var mouseX = 0;
var newTop = 0;

$("div.ls").mousemove(function(event) {
    // Getting parent offset
    var parentOffset = $(this).offset();
    // Getting child division offset
    var division = $(".ldiv").offset();
    // Calculating mouse position inside left division
    var relX = event.pageX - parentOffset.left;
    var relY = event.pageY - parentOffset.top;
    // Checking for any mouse position changes
    if (mouseX != relX){
        // Finding the new position of x-axis
        var newPosX = $(this).width() - relX - 161;
        // Calculating new height of child element in percentage
        var newHeight = 100 * parseFloat($(".ldiv").height()) / parseFloat($(this).height());
        // Displaying relevant information
        $(".coordinates").text("Mouse position = X:" + relX + " Y:" + relY + "Div offset = X:" + division.left + " Y:" + division.top  + " Width = " + $(this).width()+" newHeight = "+newHeight);
        // If the mouse moves left
        if (mouseX > relX) {
            // Making sure it doesn't go lower than 0.2 due to JavaScript rounding
            newHeight += 0.2;
            // Calculating new top so division stays in the middle of parent
            newTop = (100 - newHeight) / 2;
            // Applying new CSS
            $(".ldiv").css({
                left: newPosX + "px",
                height: newHeight + "%",
                top: newTop + "%"
            });
        } 
        // If the mouse moves right
        else {
            newHeight -= 0.2;
            newTop = (100 - newHeight) / 2;
            $(".ldiv").css({
                left: newPosX + "px",
                height: newHeight + "%",
                top: newTop + "%"
            });
        }
        // Recording the mouse position
        mouseX = relX;
    }
});

Check out a live example on jsFiddle

Goals I aim to achieve:

  1. How can I refactor this code to work more smoothly as an animation, without glitches when moving the mouse too quickly?

Answer №1

Instead of depending on mousemove, I recommend utilizing requestAnimationFrame [or a basic setTimeout]. This will significantly reduce the strain on your CPU and result in a more seamless animation.

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

sequencing the compilation of Node.js modules

I am facing an issue with my node application involving multiple interdependent modules exported using module.exports. These modules include mongohelper, transaction, server, conhandlr, and appmin. Compile order- mongohelper transaction server (..the ...

Arrange components with minimal spacing

I am currently working on a design that requires a perfectly aligned table using divs. Here is what I have done so far: My goal is to have the time section placed on the left side of the entire row, while keeping the text right-aligned to avoid creating a ...

modify the controller variable and incorporate it into the view using a directive in Angular 1.5

I need to update a controller variable from a child directive, but even after updating the controller variable, the value doesn't change in the view. Should I use $scope.$apply() or $digest? Here is my code: http://plnkr.co/edit/zTKzofwjPfg9eXmgmi8s? ...

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

Guide to creating a responsive layout using CSS and HTML

I am looking to position the main contents (content 1 and content 2) in between two side menus on my exercise page. At the moment, the main contents are overlapping with the two menus. Can someone guide me on how to fix this alignment issue? Thank you. ...

Detecting the Escape key when the browser's search bar is open - a step-by-step guide

One feature on my website is an editor window that can be closed using the Escape key. The functionality is implemented in JavaScript: $(document).keyup( function(e) { // Closing editor window with ESCAPE KEY if(e.which == 27) { // Clic ...

An error has occurred with bootstrap.js due to an issue

I encountered an issue on my website. The error message reads: Timestamp: 10/17/2012 8:27:23 PM Error: TypeError: $ is not a function Source File: path to my site/js/bootstrap.js Line: 23 If this error is caused by a conflict with another j ...

What is the reason for the exclusion of the viewport meta tag from the standard guidelines?

Emphasizing the significance of incorporating the viewport meta tag, various sources stress its role in controlling layout on mobile browsers. According to information from MDN's article Using the viewport meta tag to control layout on mobile browsers ...

Vue 2.0 custom filter not producing any output

I am attempting to create a customized filter that identifies and returns the items that correspond to a given input. It functions effectively with basic arrays like ['Apple', 'Banana', 'Cupple'], but encounters difficulty whe ...

Transferring a JavaScript variable to JSP using AJAX

I'm struggling to figure out the correct syntax to pass a JavaScript variable named "textVal" to a jsp file. Here is my code snippet: function show(textVal){ AJAX.onreadystatechange = handler; AJAX.open("POST","service.jsp",true); AJAX.setR ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method ...

Extracting props data from a component in React.js - a step-by-step guide

I am currently developing a react.js application with react-select. I have created a dropdown menu and when an item is clicked, I need to pass that item to a function that is connected to the redux store. How can I retrieve data from a component used in re ...

Creating a custom directive in AngularJS that utilizes an event listener

I am currently working on designing a custom directive that includes a text box. When a user clicks a button, the text box should expand and become focused. If the user then clicks away from the expanded text box, it should minimize, disappear, and display ...

What is the reason border-box does not function properly on inline-block elements?

Demo: http://jsfiddle.net/L5jchnpm/ I've encountered an issue where I believed that using display: inline-block would make elements act as both inline and block elements. Additionally, I thought that setting box-sizing: border-box would adjust the w ...

How can Node.js improve callback functions and integrate nodemailer for optimal performance?

I'm currently working on a new feature that involves sending a post request to download HTML pages from specific URLs, zip them, and then email the zipped file to a designated email address. The endpoint for this route looks like http://localhost:3000 ...

When attempting to insert data into MongoDB with node.js, an issue arises: "TypeError: Unable to access property 'username' of undefined."

I recently set up a MongoDB database and attempted to add data via a POST request using the Postman application. Upon successful creation of the database, a confirmation message was displayed. Here is the code snippet I used: users.js file: const router = ...

Where can I locate the Socket.IO server within the local area network (LAN)?

I am currently in the process of developing an application that facilitates connections between devices within the same network. In my design, any device can act as a server, and I aim for clients to automatically detect the server without requiring users ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...

Tips for customizing the CSS of a child component that has been imported from a different module in Angular 2

I have been using agm-snazzy-window from amg-snazzy-window There is a mention that I can modify the css class, but when I try to do so, it doesn't seem to work. Here is an example: map-component.html <agm-snazzy-info-window [closeWhenOthersOp ...