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

Exploring nested objects and arrays with Plunker - extracting their values

I have retrieved two arrays, each containing nested objects, from API endpoints. One array (preview) consists solely of numbers. For example: [{ obj1:[1, 2], obj2:[3, 4] }] To obtain strings associated with IDs, I made another call to a different en ...

What is the method used to incorporate the radial gradient in this design?

As I was browsing the internet, I came across several websites with beautiful natural gradients on their backgrounds. However, I'm puzzled as to how they achieved this effect. It doesn't seem like a simple image file because the gradient adjusts ...

Generate Sub Menu for Navigation Bar based on Main Menu Selection

I'm currently working on dynamically setting menu items and sub menu items using React Props. My code successfully iterates through the main list items navItems.label and displays them. However, I'm facing an issue with displaying the sub menu i ...

Is it possible to make a form field inactive based on another input?

I need help with disabling certain form fields until other fields are filled in. You can check out an example of what I'm trying to achieve here: https://jsfiddle.net/fk8wLvbp/ <!-- Bootstrap docs: https://getbootstrap.com/docs --> <div ...

Tips for locating all events linked to a specific text box using JQUERY

I'm currently encountering a major issue with textboxes on a page that I've been tasked to update. Whenever I attempt to input text into the textboxes, the span element next to them disappears. My application is built using ASP.NET and relies on ...

Transmit both image and JSON data in a single response using Node.js and Express

I'm in the process of building a web API using Node.js and Express and my goal is to send back both an image and JSON data in a single response. I came across a solution that involves specifying headers at , but I'm looking for a way to achieve t ...

Is there a way for me to extract the true text content that is concealed within the page source code?

Is there a way to extract the hidden text "2015-10-31" from a webpage, even though it is not visible in the page source? I am able to scrape the right side of the HTML, but I need to access the value on the left side. I have tried using Selenium to automat ...

Unexpected token "," in jQuery UI autocomplete error

Using the autocomplete feature works perfectly on my PC. However, I encounter an error when trying to test it on a mobile device. Do I need to utilize jQuery mobile in order for jQuery to function properly on mobile devices? Error message on line 3 of th ...

"Received 'grunt command not found' error even though I have successfully installed grunt and

Even after installing grunt and grunt cli, I am still encountering a 'command not found' error. { "name": "angulartdd", "version": "1.0.0", "description": "1", "main": "index.js", "scripts": { "test": "echo \"Error: no test sp ...

SyntaxError: Unexpected symbol

I have an issue with the following code: let op = data.map(({usp-custom-90})=> usp-custom-90 ) When I run it, I encounter the following error: Uncaught SyntaxError: Unexpected token - I attempted to fix it by replacing the dash with –, but t ...

Designing the Mailchimp signup form with React styling techniques

I downloaded the NPM React module for Mailchimp from this link: https://www.npmjs.com/package/react-mailchimp-form. It works well and provides all the necessary forms, but I'm having trouble customizing its style. The documentation suggests adding a ...

In ReactJS, when passing an array of objects to a child component, the first instance may sometimes return as undefined, causing the code to break

Currently, I am in the process of creating a personal blog for my brand. The "Posts" section is designed to retrieve data from a basic JSON via an API. At present, I have used mirageJS to mock the API and employed the useEffect and useState hooks to set th ...

Modifying a variable within the return statement in a React Native component

I am relatively new to React and React-native and I am facing challenges in understanding how to update a variable within the return method. Here is my current code snippet: import React, { Component } from "react"; import { View, StyleSheet, Platform, T ...

Two CSS Issues - One specific to mobile devices, the other unique to Chrome browser

Having trouble with the top banner not stretching all the way on iPhone. Any solutions? Here's a screenshot for reference: Below is the CSS applied to the div: #banner { background-color: #F7F7F7; background-size: cover; box-shadow: 0 0 ...

What is the best way to increase the spacing between buttons in a Bootstrap navigation bar?

Can anyone guide me on how to add space between each button in this Navigation Bar? I want them to be separated, similar to this example. I am using bootstrap 5. <nav class="navbar navbar-expand-lg navbar-light bg-light shadow-sm bg-body"&g ...

Issue with Bootstrap v3.3.7 panel not collapsing as expected following height adjustment

Utilizing bootstrap 3.3.7 panels, I encountered an issue when trying to slide up the panel using the icon. The panel would not hide properly once the panel height was set, resulting in only the panel content body sliding up. Here is an example: $(&apo ...

Assistance Required for Making a Delicious Cookie

Within my interface, there are two buttons displayed - one is labeled yes while the other is called no. <input type="button" name="yes" onclick="button()"> <input type="button" name="no"> In order to enhance user experience, I am looking to i ...

What is the best way to fetch Ajax information for use in several drop-down menus?

Is there a way to populate one multiple select drop-down based on the selection made in another multiple select drop-down using jQuery or ajax? Here is an example of how I am attempting to achieve this using ajax: function demo1() { var emp_id = docu ...

Display a loader while waiting for an API call to complete within 5 seconds using Angular and RxJS operators. If the API call takes longer

We are actively working to prevent user blockage during file uploads by implementing a method in Angular using RxJS. How can I display a toastr message and hide the loader if the API does not complete within 5 seconds? uploadFile() { this.service.uploa ...

Issues with plugins in Rails 4 are causing functionality to not be operating

I recently installed a template and encountered an issue with some of the JavaScript functionality. However, upon checking the compiled list of JavaScript files, I can see that all the files have loaded successfully and the CSS includes all the necessary f ...