Dynamic jQuery backstretch feature: automatic image cycling and reversing

I am currently using backstretch on my website and attempting to create a continuous loop of the moving image by automatically shifting it from left to right and back. However, I am facing difficulties as the background only moves in one direction. I am seeking guidance on how to reset or move back the image seamlessly.

How can I achieve this reset/move back effect for the image?

To view the backstretch.js code, click here.

A snippet of additional JavaScript is included below for the moving effect and initialization:

var images = ['fileadmin/template/gfx/background02-03.jpg'];
        jQuery.backstretch( images[Math.floor(Math.random() * images.length)] );
        jQuery(function($){
            (function swoop(element) {
                element
                    .animate({'margin-left':'-=5px'}, 100, function(){
                        setTimeout(function(){
                            swoop(element);
                        }, 0);
                    });
            })($('#backstretch img'));
        });

The HTML output resulting from the above code is displayed as follows:

<div id="backstretch" style="left: 0px; top: 0px; position: fixed; overflow: hidden; z-index: -999999; margin: 0px; padding: 0px; height: 100%; width: 100%;"><img src="fileadmin/template/gfx/background02-03.jpg" style="position: absolute; margin: 0px 0px 0px -3404.98890491151px; padding: 0px; border: none; z-index: -999999; width: 3006px; height: 835px; left: -551.5px; top: 0px;"></div>

Apologies for the formatting of the HTML code, bear with me as I'm not familiar with its proper handling...

UPDATE:

Thank you for the assistance provided so far, although I believe it's not exactly what I require.

My current understanding suggests that I need a calculation involving the image width and margin-left values to facilitate switching between left and right movements effectively. Thus, attempts were made to calculate the width of the image, but they returned NULL or disrupted the entire JavaScript operation.

It crossed my mind to develop a secondary function named backswoop responsible for tracking the margin-left incrementally, followed by implementing a condition based on margin-left and image-width comparisons.

iWidth = jQuery('#backstretch img').width();
jQuery(function($){
  (function swoop(element) {
    element.animate({'margin-left':'-=5px'}, 50, function(){
        setTimeout(function(){
           if(element.css('margin-left')*-1 <= iWidth){
             swoop(element);
           }else{
             backswoop(element);
           }
        }, 0);
    });
  })($('#backstretch img'));
  (function backswoop(element) {
    element.animate({'margin-left':'+=5px'}, 50, function(){
        setTimeout(function(){
           if(element.css('margin-left') >= 0){
             swoop(element);
           }else{
             backswoop(element);
           }
        }, 0);
    });
  })($('#backstretch img'));
});

Unfortunately, due to my limited knowledge in javascript, the script does not yield the desired results :-(

Answer №1

Prior to moving the element, it is recommended to utilize jQuery's .data() method to store the original margin. This allows for a seamless reset by animating the margin back to its initial value.

While this code serves as a helpful reference, it may not be flawless. It simply aims to illustrate possible approaches.

//Although global variables should be avoided, without knowledge of your codebase, it may make an exception.
swoopingElement = $('#backstretch img');
swoopingElement.data("startingmargin", $('#backstretch img').css('marginLeft'));

(function swoop(element) {
  element
    .animate({'margin-left':'-=5px'}, 100, function(){
      swoopingElement.data("timer", setTimeout(function(){
        swoop(element);
      }, 0));
    });
})($('#backstretch img'));

function resetElement(element){
  //Cease any ongoing animation first
  element.stop();
  clearTimeout(element.data("timer"));  //Even if set to zero, ensure no active timer exists.
  //Revert element to original position
  element.animate({'margin-left':element.data("startingmargin")}, 100);
  //Alternatively, for immediate reversion.
  // element.css({'margin-left':element.data("startingmargin")});
};

https://api.jquery.com/jquery.data/

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

Having trouble with CSS styling not applying to the header tag

Take a look at this snippet of HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link href="css/test.css" rel="stylesheet"> </head> <p></p> <h2>Meeting the Old Guard ...

Unable to retrieve Java variable in JavaScript

Seeking guidance on how to retrieve Json data stored in a Java variable using JavaScript. Instead of accessing the data, the html source is displayed. Java: Gson gson = new Gson(); String json = gson.toJson(obj); request.setAttribute("gsonData", gson) ...

CSS: Placing items within an ng-for loop utilizing the "fixed" position property

<ul class="nav nav-pills nav-stacked" style="list-style: none"> <li *ngFor="#el of dragZoneElems; #idx = index"> <h4 style="position: fixed; top:'idx'*10" [dragResponder]="el">{{el.first}} {{el.last}}</h4& ...

After the ajax request is made in React JS, the column vanishes from the screen

Upon querying a node.js server's PostgreSQL database, I receive specific data that needs to be displayed in two separate tables. Each table consists of two columns. However, after the AJAX call, only the first column is being populated in the first ta ...

Using both Typescript and Javascript, half of the Angular2 application is built

My current project is a large JavaScript application with the majority of code written in vanilla JavaScript for a specific platform at my workplace. I am looking to convert this into a web application that can be accessed through a browser. I believe thi ...

Can a component be passed as props and utilized within a child Component in Vue.js?

If we have components A, B, and C in a Vue 2.0 app, A declares, registers, and uses B. Can we pass C from A to B? For example: <template> <div class="A"> <B :child_component="C" /> </div> </template ...

What is the most efficient way to load a PHP page once the webpage has completely finished loading?

I'm relatively inexperienced when it comes to PHP and JQuery, so please bear with me if my knowledge is limited. Currently, I'm facing an issue where loading a small HTML table that contains information queried from game servers (like shown in t ...

An unspecified number of Ajax requests being made within a loop

Here is the dilemma I'm facing, despite trying different recommendations from StackOverflow: Situation: I am utilizing the Gitlab API to display all the "issues" in the bug tracker of a specific project on the system. Challenges: Everything wor ...

Encountering difficulties displaying navigation interface with react native navigation's stack navigator

I am trying to implement a custom side navigation bar in React Navigation without using drawerNavigator. I have fixed the side nav bar and bottom bar in app.js so that they appear on all screens. The main content area should change based on button clicks o ...

What is the process for making the default text in a text box appear grayed out?

Hey there! I have this cool idea for a text box. Basically, it starts off with default text but when you hover your mouse over it, the text disappears and you can start typing as usual: If you want to see how it looks like, you can check out this link: N ...

Using a custom jQuery function within an Angular component class

I have a custom query function that I wrote in a JavaScript file located under the source folder (/src/assets/inlineedit.js) of my Angular application. Here is the content of the file: $.fn.inlineEdit = function(replaceWith, connectWith) { $(this).ho ...

Updating Rails modal fields via AJAX on the modal index page

Currently, I am attempting to update the modal fields on the modal index page. On this particular page, there are two dropdown fields associated with each ticket. The goal is for the modal field to be updated when the value of these dropdowns changes. htt ...

Learning how to interpret the output of a jQuery post() call to a web service using jQuery and AJAX

I am currently working on sending data to a web service using jQuery's post() function. Although I have received a successful response, I am struggling to identify the specific data being returned. This is the code I have written so far: var response ...

After receiving the response, the Ajax success function does not run as expected

I have written the following code: $(".simpleCart_shelfItem button").click(function() { $(this).prop('disabled', true); $(this).addClass('disabled'); $(this).html("Adding &nbsp;&nbsp;<i cl ...

PHP Ajax login form to instantly authenticate without redirecting to a new page

After attempting to implement Ajax in my login form by following two different tutorials, I am still facing the issue of error messages redirecting to another page instead of displaying on the same page. I have tried to troubleshoot and compare my code wit ...

Storing items in localStorage in the same order they were added

I am having an issue with sorting localStorage items by the order they were added. Despite my code working to add items to the localStorage array and display them as HTML, I am encountering a problem with the order of the items. When I add a 3rd item to t ...

Encountering a reload error while refreshing the Angular page

Whenever I click on a deck from my list, the corresponding deck-detail component is supposed to load and display the details of the selected deck. The URL should also change to something like "deck/id/deckName". However, if I try to reload the page or copy ...

Continuously executing a series of JQuery functions or iterating through them repeatedly

Struggling with a jQuery animation loop issue that has me stuck. I need the animation to repeat continuously, but it's not working despite trying setInterval. Can anyone assist? Here's the fiddle link: https://jsfiddle.net/8v5feL9u/ $(document). ...

What is the solution for resolving AngularJS URL encoding?

Currently, my AngularJS app utilizes a component known as navbar to house the searchbar along with a search() function. $scope.search = function (keyword) { console.log(keyword); $state.go('main', { keyword: keyword }, ...

Is there a way to execute this process twice without duplicating the code and manually adjusting the variables?

I'm looking to modify this code so that it can be used for multiple calendars simultaneously. For example, I want something similar to the following: Here is what I currently have: This is my JavaScript code: var Calendar = { start: function () ...