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

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...

Encountering an error with the message "SyntaxError: missing ; before statement" while attempting to utilize the Google Place Search

Lately, I've been encountering a 'SyntaxError: missing ; before statement' error while attempting to execute this ajax code in order to retrieve all nearby ATMs within a 1 km radius. var url = "https://maps.googleapis.com/maps/api/place/nea ...

Unforeseen outcomes of JavaScript when using the let and var keywords

In JavaScript, when using the var keyword to declare a variable, the JS engine assigns a default value of "undefined" at creation stage. console.log(message); // undefined var message = "My message"; However, with the let keyword: console.log(message); ...

Preventing Vue.js SPA from accessing cached version when JWT expires: the solution

I'm encountering an issue with my Vue.js / Express application that I can't seem to resolve. Here's how the process unfolds: An unauthenticated user logs into the app and is presented with the login page. Once successfully authenticated, t ...

numbered navigation jquery plugin

Can anyone recommend a jQuery plugin or alternative solution for creating a navigation system for comments similar to YouTube? Here is the link for reference: Thank you in advance. ...

Error: You can't call .text as a function in jQuery

While trying to retrieve the text from my td, I encountered the following error: $tds[2].text is not a function. The output of console.log('td',$tds[2]) shows: https://i.stack.imgur.com/OUngP.png $(document).ready(function() { $trs = $(&ap ...

Displaying divs inline with overlapping child divs

As a beginner in CSS, I tackle the challenges of learning it every day. Despite feeling clumsy and not naturally adept at it, my determination is strong (although sometimes my brain feels like an old computer on the verge of overheating). My current goal i ...

UI binder is having difficulty resolving CSS

After creating a search panel for my application using UI binder, I noticed that the desired behavior is not being achieved. Ui.xml <g:HTMLPanel> <c:SimpleContainer> <c:InfoContainerHeader text="{labels.searchFilter}" /> ...

Issue "Excessive large sharp variable amount" encountered during ajax request

I'm attempting to retrieve data from a different domain using jQuery. Take a look at the code snippet below: $.ajax({ type: "GET", dataType: "script", url: "http://www.example.com/ajax.php", data: 'id=5', success: functi ...

Troubleshooting problem with AJAX in Rails 3.0.10: Investigating create.js.erb script

Embarking on my journey into web development, so please bear with me. My first foray into app creation led me to Rails 3.0.10 Attempting to integrate AJAX into a micropost form has been my current challenge. I've ensured the controller set up is co ...

Steps for configuring jQuery hide(), adding Class, and remove Class for flawless execution

My HTML Code is structured as follows : ... @foreach($hotel as $key=>$value) ... <div class="iteration"> <input type='hidden' value='<?php echo $value['HCode'].'#' ...

Restrict the number of rows in a CSS grid

Hello there, I am in the process of creating an image gallery using CSS grid. Specifically, my goal is to initially show just one row of images and then allow users to click a "Show more" button to reveal additional images. You can see my progress here: ...

[CSS] What's the trick to getting it to smoothly glide to the top?

As a new designer, I have a question about how to make the background color extend to the top without any white space. Can someone please guide me on how to achieve this? <!DOCTYPE html> <html> <head> <style> body{ margin: 0px; p ...

What could be causing the issue with sending data via Ajax when using the `type="password"` input?

Why does sending data using ajax with input type="password" not work? The main idea is that when I fill in a password less than 6 characters, it should display Password minimum 6 characters I tested this code and found that it was not working. So, I edit ...

Transitioning from using sendfile() to sendFile() function within the Express framework

Here is the code snippet I am using: router.get('/image',(req,res,next)=>{ const fileName = "path_to.jpg" res.sendfile(fileName,(err)=>{ if (err) { next(err); } else { console.log('Sent:', fileName); } ...

Issue with fixed positioning on iPad devices

A unique feature we implemented on our site is a small control that is positioned at the bottom of the screen. However, upon viewing the site on an iPad, the control does not stay fixed at the bottom but rather floats in the middle. What's the issue ...

Exploring nested JSON data in Vue.js

In my attempt to access nested JSON within an array using Vue for a simple search functionality, I encountered a problem. Each school is encapsulated in a "hit" array, causing the system to perceive only one result of "hit" instead of returning data for ea ...

Once the auto-suggestion feature has completed its task

Utilizing the autocomplete Plugin, I have encountered an issue despite its great functionality. $('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)&bsol ...

activating a button following the selection of a checkbox

My code includes a submit button that is currently disabled. I am looking to enable it when the user clicks on the "I agree" checkbox using jQuery. Can someone assist me with this? My code is written in HTML, JavaScript, and jQuery. <input id="agree" ...

Implementing background images with jQuery

Within my coding script, there is a variable called image_src which is defined as: var image_src = 'img/test.jpg'; I attempted to set a background-image to a block using jQuery with the following code: $('#lightbox').css({ &a ...