Animating the scaling of a background image with JavaScript resulted in a jittery, unstable image

I'm encountering a shaking effect when I animate a DIV container with a background image using JS. How can I make the animation smoother?

$('body').on('click', '#container', function() {
  $("#container").animate({
   "background-size": 1000 + "px"
  }, 4000);
});
#container {
  width: 500px;
  height: 300px;
  margin-top: 100px;
  margin-left: 100px;
  background-color: #eeeeee;
  background-image: url("https://real-e-expo.com/img/609/m5d2c42466d2e9.jpg");
  background-repeat: no-repeat;
  background-position: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>

Check out the JSFiddle link for reference: https://jsfiddle.net/rn6kwup0/

Answer №1

To achieve a smooth scaling effect, you can utilize CSS3 transforms. Here is an example that demonstrates this technique:

https://example.com/your-demo

.box {
    width: 400px;
    height: 200px;
    margin-top: 50px;
    margin-left: 50px;
    background-color: #f0f0f0;
}

.box .image {
    width: inherit;
    height: inherit;
    background-repeat: no-repeat;
    background-position: center;
    background-image: url("https://example.com/image.jpg");
    transform: scale(0.5);
    transition: all 2s ease;
    background-size: cover;
}

.box.animate .image {
    transform: scale(1.5);
}

Answer №2

The movement is caused by the absence of hardware acceleration during repainting. When creating animations, it is crucial to select specific properties to animate in order to enhance performance. Opting to animate the transform property is a more efficient choice compared to animating background-size.

In order to transition from a smaller size to a larger size, I modified the jQuery animate() function to a simple css() alteration by adjusting the scale transformation. The value within the scale() function indicates the new size. For instance, 2 represents 200% of the original size in this case.

$("#container").css({
  "transform": "scale(2)"
});

The inclusion of the transition property in the CSS enables control over the duration and easing of the change. By implementing this method in a div with overflow: hidden, the desired background-image effect can be achieved.

$('body').on('click', '#container', function() {
  // opting for transform over animating background-size
  $("#container").css({
    "transform": "scale(2)"
  });
});
#container {
  width: 500px;
  height: 300px;
  margin-top: 100px;
  margin-left: 100px;
  background-color: #eeeeee;
  background-image: url("https://real-e-expo.com/img/609/m5d2c42466d2e9.jpg");
  background-repeat: no-repeat;
  background-position: center;
  /* adjust transition speed here, with the second value representing duration */
  transition: all 3s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>

Answer №3

Make sure to set the initial state background-size and include easing for a smooth animation effect. Here is the code snippet that demonstrates this:

   $('body').on('click', '#container', function() {

        $("#container").animate({
            "background-size": 100 + "%"
        }, {duration: 9000,
      easing: "linear"});


    });
    #container {
        width: 500px;
        height: 300px;
        margin-top: 100px;
        margin-left: 100px;
        background-color: #eeeeee;
        background-image: url("https://real-e-expo.com/img/609/m5d2c42466d2e9.jpg");
        background-repeat: no-repeat;
        background-position: center;

        background-size: 10%;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div 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

Identify the absence of search results in an Ajax request to the search page before rendering the HTML content

I am attempting to retrieve JSON code from a page using the following PHP function: private function __ajax_admin_search($username = '') { $result = $this->admin_login->Admin_Username_Ajax($username); $count = count($result); for ...

Utilize images stored locally in ReactJS

My path to the image is: ../src/assets/images/img_name.jpg" And my path to the file.js is: src/file_name.js If I include the following code in file.js: Import img_name from "../src/assets/images/img_name.jpg" Then reference the image pa ...

Creating a new row does not result in the creation of a new span displaying the character count message

Every description field should have its own character counter, with different SpanIDs displayed in respective SpanIds for each new row. How can this be achieved? <div class="row"> <div class="col-s ...

Animated CSS sidemenu (utilized as a filtering panel for a table)

Hi there, I'm having some trouble with CSS Animation. I recently started developing websites and am using Bootstrap 4 along with Animate.css for animations. My goal is to have an icon button expand sideways to reveal a div containing select elements f ...

When you click on the logo, it will automatically redirect you to a designated Bootstrap Tab and set that tab

After searching through numerous posts, I am still struggling to find a solution to my straightforward issue. My requirement is simple: when a user clicks on the brand (logo), it should not only redirect them to a specific tab but also make it appear as a ...

While attempting to use JavaScript and AJAX to read a JSON object, I encountered an issue caused by the CORS

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Docu ...

What's causing the member to be undefined?

client.on('raw', (e) => { if (e.t === 'MESSAGE_REACTION_ADD' && e.d.message_id === '813150433651851265' && e.d.emoji.name === "✅" ) { const guild = client.guilds.cache.get(e.d.gui ...

Decorative initials have a tendency to create spaces within the text

I have incorporated Google Fonts into my website, along with Bootstrap. Here is the code I am using: .initial { font-size: 1.5em; font-family: 'Euphoria Script', cursive; } p { font-family: 'Open Sans', sans-serif; } <html> ...

The font color fails to change when hovering over

I'm experiencing an issue with the styling of my input box. When the user starts typing, a div containing a list of possible clubs is displayed. Currently, I am having trouble with the .clubLink:hover class and its background color. CSS: <style& ...

Using bootstrap's center-block class, you can easily center

I'm attempting to center the content of a form. <div class="login-container"> <div class="center-block"> <form action="/joinChart" method="get"> <input name="username" id="username" type="text"><br><br> ...

I need help figuring out how to navigate between different pages in my Vue-cli app that has multiple pages configured

After following the guide on https://cli.vuejs.org/config/#pages, I successfully configured vue-cli3 to build a multiple page application. My project consists of 2 static pages, and I set up the vue.config.js file as shown below. However, when running the ...

Jumping Sticky Table Headers

Looking for a solution to prevent the table header from moving when scrolling through the data: tbody { overflow-y: scroll; } thead, tbody tr { display: table; width: 100%; table-layout: fixed; text-align: left; } thead, th { position: sti ...

What is the best way to activate an input field in react-select?

Currently, I am working on a dropdown feature using react-select and have encountered some issues that need to be addressed: 1) The input field should be focused in just one click (currently it requires 2 clicks). 2) When the dropdown is opened and a cha ...

When utilizing an 'imported' asynchronous function, make sure to clean up the useEffect

Please do not mistake this for a duplicate. Despite my thorough search on various blogs and sources, I have yet to find a solution. My primary question is 'how can I address the error of react state change in unmounted component, and also cancel an a ...

How can Three JS and an image be combined to make a custom 3D cookie cutter?

I am currently working on a project that involves extracting the edges of a black and white image. My goal is to then generate a 3D model that highlights the edges of the black shape, extrudes the edges for depth, adds thickness to the walls, and creates ...

Switching between sockets on a rotational basis

Imagine there is a division in the HTML file, and an interesting game is being played where each player has the opportunity to change the color. However, there’s a twist – they can only switch colors after the other player has taken their turn. The pla ...

The Node.js application is unable to locate the source file path

Currently, I am in the process of creating a simple quiz application. While working on this project, I encountered an issue with linking a JS file in an HTML template. Even though I have confirmed that the path is correct, every time I run my node app, the ...

Populate the content within a div element with specified height and width by utilizing JavaScript and jQuery

I need help with filling a fixed height div with long text retrieved via ajax in json format. For example, if I have a div with a height of 500px and width of 300px, with a font size of 16px. Is there a javascript recursive method that can fill the data ...

Generating a dynamic triangle within a div while ensuring it fits perfectly with the maximum width

I need help with creating a responsive triangle on a web page that takes three inputs. The challenge is to adjust the size of the triangle so it fits inside a div element while maintaining the aspect ratio of the inputs. For instance, if the inputs are 500 ...

Creating a legitimate string using a function for jqGrid editoptions value: What's the best way to do it?

I am encountering an issue while trying to create a string for the editoptions value using a function. The desired string format is as follows: '1:Active;2:Inactive;3:Pending;4:Suspended'. Strangely, when I manually input this string as the value ...