How to use jQuery Animate to create a step-by-step animation with image sprites?

I'm working on creating an image sprite using jQuery and I'm curious if it's feasible to animate it in steps rather than a linear motion. I initially tried using CSS3 animations, but since IE9 is a requirement, the animations didn't work properly in that browser.

The sprite I have consists of 12 frames, each frame being 280px X 280px. My goal is to utilize jQuery to animate the sprite upon mouseover and mouseout in increments instead of smoothly sliding the background image.

Below is the code snippet I am currently using:

<div class="window"></div>

CSS:

.window {
    width: 280px;
    height: 280px;
    background: url("http://s27.postimg.org/neu6mvztf/single_hung_door.png");
}

JS:

$(".window").hover(
    function () {
        $(this).animate({
            'background-position-x': '0',
            'background-position-y': '-3080px'
        }, 1500, 'linear');
    },
    function () {
        $(this).animate({
            'background-position-x': '0',
            'background-position-y': '0'
        }, 1500, 'linear');
    }
);

JSFiddle with sample of desired effect

Is it possible to achieve this type of animation with this approach? Thank you!

Answer №2

This code may not be the most concise, but essentially, it involves implementing a continuous animation loop that shifts the frame by one every x milliseconds. The original fiddle you referenced animates the entire strip in a linear manner. You can find the modified version on the jsFiddle link below.

var currentY = 0;
var isAnimating = false;
var $window = $('.window');
var windowWidth = 280;
var frameRateMs = 60;

function updateWindow() {
    if (isAnimating) {
        $window.css({'background-position-y': currentY + 'px'});
        currentY -= windowWidth;
        if (currentY == -3080) {
            windowWidth = -280;
        } else if (currentY == 0) {
            windowWidth = 280;
        }
    }
    setTimeout(updateWindow, frameRateMs);
}

$window.hover(function() {
    isAnimating = true;
}, function() {
    isAnimating = false;
});

updateWindow();

http://jsfiddle.net/64nu4h4w/10/

Answer №3

To maintain the structure of your code, I have introduced a new function called .animateSteps():

$(".panel").hover(
    function () {
        $(".panel").animateSteps(350,-350,25);
    },
    function () {
        $(".panel").animateSteps(4000,350,25);
    }
);


$.fn.animateSteps = function(final,step,duration) {
    if(typeof timer !== "undefined") clearTimeout(timer);
    var element = $(this);
    if(parseInt(element.css('background-position-x')) === final) return;
    element.css('background-position-x', '+='+step+'px');
    timer=setTimeout(function(){element.animateSteps(final,step,duration);},duration);
}

This function requires 3 parameters:

  • final: the final position in pixels

  • step: the amount of pixels to move at each step

  • duration: the time interval between iterations

JS Fiddle Demo

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

Execute the component function located within one page using another page

Can someone help me understand how to trigger OnSwipe from inside a different JS file named CardFooter.js? This file contains a button with an OnClick event that triggers OnSwipe from the preceding JS file called CardItem.js. Both of these files are includ ...

Error: Unable to define $scope function in Angular and Jasmine integration

I am currently working with a controller var videoApp = angular.module('videoApp', ['videoAppFilters', 'ui.unique', 'angularUtils.directives.dirPagination']); videoApp.controller('VideoCtrl', function ($sc ...

Creating a dynamic drop-down menu using a single database table in CodeIgniter

Table https://i.sstatic.net/yw7d0.jpg I need the district names to dynamically change based on the Category selection. For example, when I select Category 1 from the drop-down, only the district names under Category 1 should be displayed, and the same fo ...

Previewing multiple images with multiple file inputs

I am trying to find a way to preview multiple images uploaded from different inputs. When the button is pressed, the content from a textarea containing <img src="$img" id="img1"> is written inside a div called seeimg. The IDs for these images range f ...

AngularJS expression utilizing unique special character

There are certain special characters (such as '-') in some angular expressions: <tr data-ng-repeat="asset in assets"> <td>{{asset.id}}</td> <td>{{asset.display-name}}</td> <td>{{asset.dns-name}}</td&g ...

React conditional statement within a map function embedded in a JSX element

Below is the function I have created to generate tabbed items: function ConstructTabs(props) { const tabs = props.tabs; const makeTabs = tabs.map((tab, index) => { <React.Fragment> <input className="input-tabs" id ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

Navigate to link based on selected option in Bootstrap select menu

How can I make a page redirection based on the selected option value from a bootstrap select? Here is the HTML code: <select class="selectpicker"> <option value="https://example.com/">Home</option> <option value="https://exam ...

What is the process for changing the color of my input fields to black and text to blue?

<form method="post" action="https://ip/form.php"> First name<br> <input type="text" name="fname" value=""><br> Email Address:<br> <input type="text" name="email" value=""><br> Phone: <br> <input type="text ...

The search and sorting functionality in jquery DataTables is malfunctioning

I am facing difficulties with sorting and filtering the datatable as none of the JS functions seem to be working properly. I have already included the necessary JS files. Here are some details: I am connecting to a database to retrieve data in JSON format. ...

Exploring High-Density Mobile Devices with Bootstrap 3 Landscape Mode

After completing my first Bootstrap site using version 3, I noticed a display issue when viewing it on an iPhone 5 or LG G2 in landscape mode due to the pixel density. This was not a problem with the Responsive Grid system I previously used. Although I sp ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

Utilizing ChartJS to convert a chart into a Base64 image within a Vue environment

I am currently utilizing the PrimeVue chart component, which is built on top of ChartJS. The configuration is very similar. The documentation indicates that I need to instantiate a new Chart() and then call toBase64Image(); My main query is, how do I ac ...

Issues arise with dynamic content when implementing the jQuery mobile framework alongside the risky swiper library

I have been working on a jQuery mobile web application where I attempted to integrate the dangero.us swiper. Despite filling my swiper-container with dynamic HTML and using the reinit() function as recommended in other tasks, nothing seemed to happen. Her ...

Obtaining the header with jQuery leads to receiving no content

Forgive me for the odd request, but I am currently utilizing the jQuery Cycle plugin on a WordPress platform to incorporate a custom post type as a banner image with accompanying text. Rather than the typical pagination format of "1 2 3 4..." etc., I aim t ...

Eliminate the curved edges from the <select> tag

Is there a way to eliminate the rounded corners on a select element? I attempted using the code below, but it resulted in removing the arrows and cutting off the bottom of the placeholder text: select { -webkit-appearance: none; -webkit-border-radius ...

Navigational highlighting of current page section on a one-page website

I'm struggling with adding a navigation bar feature that will highlight the current section being viewed on my website. All I want is for the currently viewed section to appear bold in the navigation bar. Check out the codepen link: HTML <na ...

The return type of a server-side component in NextJS 14 when it is asynchronous

When using NextJS 14, I encountered a problem with the example provided in the documentation. The example is within the Page component, typically typed as NextPage. However, this type does not support the use of async await server components. In my case, ...

Sequential selection in Node-firebird is non-functional

I've been testing some simple code sequentially using the Firebird library called "node-firebird." Despite having multiple rows, it only returns 1 row every time. exports.sequentially = (select, db_con_options) => { Firebird.attach(db_con_options, ...

Designing a visual showcase with interactive tab links for image selection

I have been working on developing an Angular component that simulates a tab gallery functionality, inspired by this example. Below is my HTML structure: <div class="gallery-container"> <div class="display-container"> ...