Can you provide a tutorial on creating a unique animation using jQuery and intervals to adjust background position?

I am attempting to create a simple animation by shifting the background position (frames) of the image which serves as the background for my div. Utilizing Jquery, I aim to animate this effect. The background image consists of 6 frames, with the first frame starting at 0,0px, the second at 85px,0, and so forth. My goal is to smoothly transition between these frames until the stop button is clicked. Below, you can find my jquery code. Within the code, I have set up an array to track the number of pixels to move across. Each frame should maintain a duration of 1000 milliseconds before transitioning to the next frame. Despite my efforts, there seems to be an error in my implementation that I can't seem to identify. Take a look at my code snippet:

$(document).ready(function () {
    var timer;
    $("#clickMe").click(function() {
        //alert("you are here");
        timer=setInterval(moveframe,1000);
    });
    $("#stop").click(function() {
        clearInterval(timer);
    });
});

function moveframe() {
    var framespx=[0,85,172,256,512,1024];
    for (var i=0;i<framespx.length;i++) {
        alert("you ar here");
        var xPos=framespx[i]+"px ";
        var yPos="0px";
        $('.fixed').css({backgroundPosition: xPos+yPos});
    }
}

Answer №1

Your code seems to be experiencing a logical error as when you run it, only the same background is displayed.

Here is a suggested fix:

$(document).ready(function () {
    var timer;
    $("#clickMe").click(function() {
        //alert("you are here");
        timer=setInterval(moveframe,1000);
    });
    $("#stop").click(function() {
        clearInterval(timer);
    });
});
var j=0;
function moveframe() {
    var framespx=[0,85,172,256,512,1024];
    for (var i=0;i<framespx.length;i++) {
        if (j%framespx.length == i){
            alert("you ar here");
            var xPos=framespx[i]+"px ";
            var yPos="0px";
            $('.fixed').css({backgroundPosition: xPos+yPos});
            j++
            break;
        }
    }
}

Answer №2

 css({'background-position': xPos+' '+yPos});

I find the attribute value above a little confusing, but I am hoping it is correct with more certainty.

css('background-position-x', xPos);
css('background-position-y', yPos);

I believe that a for loop may not be necessary in this case.

var posAry=[0,85,172,256,512,1024];
var currPos=0;
var timer;
$(document).ready(function () {

    $("#start").click(function() {       
      timer=setInterval(move,1000);        
   });
   $("#stop").click(function() {
     clearInterval(timer);
   });
});


function move() {  
  $('.fixed').css({'margin-left': posAry[currPos]+'px' }); /**you can change it to background position/padding/... as needed by you**/
  currPos++;
  if(currPos==(posAry.length))
    currPos=0; // for looping back
}

http://jsfiddle.net/7PvwN/1/

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

Converting HTML divs into a single page PDF document using DinkToPdf

Having trouble generating PDF from HTML using DinkToPdf due to div elements splitting across pages? Is there a way to ensure the entire div stays on one page, perhaps through html/css? Ideally, if there is sufficient space, the div should remain on the c ...

What is the best way to display a child component inside an iframe using Vue.js?

Looking to provide a live preview of an email before sending it out, I've opted to use an iframe to contain the preview and prevent style leaks. The goal is for the preview to update dynamically as the user fills out form details. How can I display a ...

Errors occurred when trying to use Jquery to handle a JSON response

enter code here function customPaging(action, action1, page) { alert("in customPaging"); $.getJSON("./paging.do?action="+escape(action)+"&p="+escape(action1)+"&str="+escape(page), function(data){ alert("Length: "+data.length); var options = ...

Angular Starter Kit

When starting with Angular.js, there are various boilerplate kits available such as angular-seed, some incorporating requirejs and more. However, many of the options I've come across seem to be outdated. As a newcomer to Angular, I'm wondering if ...

ReactJs Unicode Integration with ID3 JS

I am working on a React Project that involves using an input type = "file" to upload music files. I am able to extract tags using ID3 Js, but the result is displayed in this format: https://i.stack.imgur.com/192co.png Is there a way to convert ...

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

Arrangement of Columns in a Vertical Bootstrap Layout

When the xs layout displays as expected, how can I move the sidebar up to the navigation in order to eliminate the gap between them in the lg layout? <div class="row"> <div class="col-xs-12 col-lg-3 col-lg-push-9"> navigation & ...

Utilizing the Django object array in AngularJS – a comprehensive guide

I have a Django variable structured like this: [<Topic object>, <Topic object>] When passing it to Angular using ng-init, I wrote the following: <div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} "> However, ...

Having Trouble with Jquery UI Autocomplete and JSON Integration

Hi everyone, I'm currently investigating why the autocomplete() method is not performing a GET request when I append a variable to the end of the source URL. Here's an example: <script> $(document).ready(function(){ var se ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

Expanding divs automatically depending on the content they contain

Currently, I have been developing a template for a database-driven page that is supposed to contain four divs for content arranged like this: ----- ----- | 1 | | 2 | ----- ----- ----- ----- | 3 | | 4 | ----- ----- The information in each box will always ...

Transform the JSON structure with the power of JavaScript

Seeking assistance in converting the following array of JSON using either javascript or jquery: [ [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"Packet"}], [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":4 ...

Clicking on text within a DIV using jQuery

How can I use jQuery to show an "alert" when text inside a DIV is clicked, excluding images and other tags? The texts are contained within various DIVs along with images and tags. Is there a way to achieve this using jQuery? Check out the jsFiddle example ...

Attempting to retrieve the MongoDB data for the designated field (data.site.alerts.alert) and transfer it to the client side

*****My code ***** import logo from './logo.svg'; import './App.css'; import React, { Component } from 'react'; import axios from 'axios'; export default class App extends Component { state = { arraydata: ...

PHP/jQuery search field

I am currently working on creating a search box using php and jquery to retrieve search results from a database. My goal is to have the search query triggered as the user types into the search box, finding data that matches the keywords entered by the user ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Cross domain request in a simple HTML document

I'm currently working on an app that is strictly in plain HTML files without a server. I'm facing difficulties with cross domain requests from JavaScript. Whenever I try to make a request, the browser displays this error message: XMLHttpRequest ...

Unexpected event triggering

I have come across a snippet of code that allows me to retrieve URL query strings var QueryURL = function () { var query_url = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i< ...

What is the best way to display pages with different states in ExpressJS?

Here is a code block that I have: var express = require('express'); var newsRouter = express.Router(); newsRouter.get('/:news_param', (req, res) => { let news_params = '/haberler/' + req.params.news_param; req.ne ...