Tips for resolving flickering animations in CSS and JavaScript

Is it possible to dynamically set a scale and margin for an element in order to center it fluidly using the wheel event? I am aiming to achieve a smooth transition while also adjusting scroll position on the wrapping element in a fluid manner.

In the provided jsfiddle example, I have utilized the CSS transition attribute to create a fluid effect. However, there seems to be an issue where the margin animation triggers faster than the scale adjustment, causing the div to initially move sideways. This can be observed especially when zooming in with greater intensity. How can this be rectified so that the cross located in the middle of the image does not shift sideways during zoom in and out?

To view the problem clearly, simply use the mouse scroll once and then repeat the action at the end of the animation.

To address this issue, I followed Gabriele Petrioli's solution but still required further information regarding the positioning of the element. As a result, I decided to integrate the margins into the CSS transform attribute through the 'translate' option, which appears to be functioning correctly.

I made the following modification:

$el.css({
    'transform': "translate(" + t + "px, " + l + "px) scale(" + scale + ")",
});

For more insight, you can refer to the updated jsfiddle.

Answer №1

To center the element, I recommend using absolute positioning right from the start.

Here are some adjustments:

  • Utilize position:absolute along with left/right to align it in the center
  • Use transform: translate(-50%, -50%) to align the grid center with the wrapper center
  • Set the origin to 50% 50% so that you don't have to calculate movement
  • Since margins are not needed anymore, focus on adjusting the scale
  • Added a Math.max/Math.min function for maintaining sanity during testing
var scale = 1;
var $wrap = $('#wrap');
var $el = $('#el');

$(function() {
  $el.on('wheel', function(e) {
    e.preventDefault();
    
    scale = e.originalEvent.wheelDelta > 0 ? scale * 1.5 : scale / 1.5;
    scale = Math.min(Math.max(scale, 0.2), 20);
    
    $el.css({
      'transform': `translate(-50%,-50%) scale(${Math.max(scale, 0.1)})`,
    });
  });
});
#wrap {
  position: fixed;
  width: 400px;
  height: 300px;
  background: pink;
}

#el {
  position: absolute;
  width: 200px;
  height: 200px;
  text-align: center;
  line-height: 200px;
  transition: transform 1s;
  transform-origin: 50% 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-image: radial-gradient(circle at 0px 0px, #666 1px, transparent 0);
  background-size: 4px 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<html>
  <div id="wrap">
    <div id="el">
      +
    </div>
  </div>

</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

Laravel: The current configuration does not support the experimental syntax 'classProperties' at this time

When compiling my javascript files using npm run dev, I encountered a warning in my resource/app.js file where I require my custom validation script. The warning stated the following: Module build failed (from ./node_modules/babel-loader/lib/index.js): Syn ...

Enhance your SVG progress circle by simply selecting checkboxes

I have a unique system with 5 checkboxes that act as a To-Do list. When I click on each checkbox, the circle's diameter should progressively fill up in increments of 1/5 until all 5 checkboxes are completed. The order in which the checkboxes are click ...

Ways to format table using flex-wrap sans the use of flexbox

My HTML and CSS structure is as follows: .item { background: white; padding: 5px; display: inline-block; text-align: center; } .item > div { background: yellow; width: 60px; height: 60px; border-radius: 50%; display: table-cell; ...

Achieving the desired results through the utilization of CSS3 rather than relying on images

I am currently exploring the use of CSS3 to create a menu instead of relying on images over at . You can view my progress and code (including images and styles) here: Although I attempted to use CSS3 for the border shadow and matching the background of ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

Tips for keeping a dynamic height div in place without affecting surrounding elements

HTML: <div id="autocomplete" hidden></div> <input type = "button" id = "search" value = "Search"> The autocomplete div contains dynamically generated input tags created by jQuery. These input tags cause the button to be shifted down the ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

"Troubleshooting: Issues with jQuery Counter Functionality

Hey there, I'm new to JavaScript and jQuery! I've got this form set up with Bootstrap's disabled class: Note: the 'disabled' class in bootstrap properly disables and enables the button based on conditions. <form action="" met ...

Creating a dynamic select functionality in Drupal forms

Being more focused on backend development, I am facing a challenge that may be simple for jQuery experts. In Drupal, I have two arrays - one containing names of views and the other having displays for each view. To populate these arrays, here is the code s ...

Using JavaScript variables within an HTML tag

I am attempting to embed a JS variable into HTML tags, but for some reason the movie is not loading. Here is the code I am using: var filmLocation = "images/main.swf"; <script>document.write('<PARAM name="movie" value="' + filmLocat ...

Executing a controller method in Grails using JavaScript

When working in a Grails view, I find myself needing to execute a JavaScript method to retrieve certain information. To achieve this, I have set up a submit action as shown below: <input type="submit" name="submit" class="submit action-button" value="G ...

Deploying a single node.js app on two separate servers and running them simultaneously

Is it possible to set up my game to run on both the west coast and east coast servers, while still using the same domain? In my code structure, app.js runs on the server with the home route serving as the entry point for the game. This means that users si ...

Sort the array based on the enum name rather than its value

Below is an example of an enumeration: export enum Foo { AA = 0, ZZ = 1, AB = 2, ER = 5 } In my case, I want to sort my Bars based on the name of the enum (AA, AB, ER, ZZ), rather than the numerical value (0, 1, 2, 5) that they represent. ...

The module in Node.js is unable to be loaded

Dealing with a common problem here. Despite trying to reinstall npm, deleting node_modules files and package-lock.json, the issue persists. The console output is as follows: node:internal/modules/cjs/loader:1080 throw err; ^ Error: Cannot find module &apo ...

There appears to be a malfunction with certain hyperlinks on the table

There seems to be an issue with the four links in the third column, first, second, third, and fourth rows (Order Form PDF, Rental App PDF, Married Rental PDF, and Consent Form PDF) as they are not functioning properly. Below is the provided code snippet: ...

Retrieving a JavaScript variable from a Python Selenium request

Currently, I am utilizing Python in conjunction with Selenium to monitor changes on our pbx system. A specific value that I require is being retrieved through a JavaScript call and unfortunately, it is not directly written into the HTML code. This has made ...

Sharing information between pages in React through Router

I am struggling to transfer a single string from one page to another using react router and only functional components. I have created a button that links my pages, but I can't seem to pass the string successfully. Here is an example of the code on th ...

Place a "sticky" button directly below a second "sticky" navigation bar

Within my app file, I have customized components like an appbar and various page elements: const styles = theme => ({ appBar: { width:'100%', }, }); class App extends Component { render() { const {classes} = this.props; ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

Is it possible to utilize a contenteditable div in place of a textarea?

Is it possible to replace a textarea with a content editable div? Will the behavior be the same? Can data processing be done in the same way as with textarea data? ...