Ways to halt the animation on a background image

I am facing a challenge with the animation on the background image of my website. The image is constantly moving to the left, and when it reaches the end, it starts over. However, I would like the image to switch direction when it reaches the edge - going right when reaching the left side and vice versa.

var x=0;
var y=0;

var banner = $("#loading");
banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');

window.setInterval(function(){
  banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');
  x--;
}, 90);

Answer №1

Check out this cool animation:

let position = 0;

const fps = 30;
const speed = 2;

const bannerWidth = 400;
const imageSize = 128;

setInterval(function() {
    position += speed;

    if (position >= bannerWidth - imageSize || position <= 0) {
        speed *= -1;
    }

    $("#banner").css("backgroundPosition", position + "px 0");
}, 1000/fps);
#banner{
    width: 400px;
    height: 128px;
    border: 1px solid blue;
    background-image:url("https://example.com/image.png");
    background-position:0 0;
    background-repeat:no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner"></div>

If you provide your HTML & CSS, I can adjust the example accordingly.

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

Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side. Any advice on extracti ...

What is the solution to prevent ahref from voiding the jQuery modal box?

I'm encountering an issue with a pop-up box triggered by <a>. I want to include content with links using <a> tags inside the box, but when I add another <a href>, it causes the entire box to break and reveals all the hidden content, ...

What is the best way to trigger a method in Angular when a user leaves an input field blank?

I have implemented controller methods to trigger upon changes in this specific input field: <input type="text" ng-model="query" ng-model-options='{ debounce: 500 }' ng-change="searchOnTags(query)"/> Is there a way to call a separate metho ...

Mastering the art of changing text color based on element class name in CSS3

Is it possible to dynamically set the text color of a list item based on the class name of its nested span element? For example, if the span has a class of "green", the text color of the parent li should also be green. How can this be achieved? Demo:https ...

Is there a way for me to access the current templating in AngularJS?

I am looking to retrieve the HTML page as a string after AngularJS has finished rendering the template. My goal is to send this content to the server. .controller('MyCtrl', ['$scope', '$location', function ( $scope, $location ...

Creating a responsive navigation bar with Bootstrap步 is simple and effective

Thank you for taking the time to review my current code. The main issue I am encountering pertains to the responsiveness of the navbar. Whenever I zoom in or out, certain elements tend to lose their alignment and aesthetic appeal. Specifically, the navbar ...

Including a PHP file after successful AJAX request

In my div class called news, I showcase updates submitted by users. My goal is to have new updates appear at the top of the news section when a user submits one. I attempted the following approach, but it didn't produce the desired outcome. Upon form ...

Having trouble displaying Google Map using GMapPanel in EXTJS 4?

Ext.Loader.setPath('Ext.ux', '../ux'); Ext.require([ 'Ext.tree.*', 'Ext.data.*', 'Ext.window.MessageBox', 'Ext.window.*', 'Ext.ux.GMapPanel' ]); var map = new Ext.ux ...

Challenges with arrays that occur asynchronously

At the end of this code snippet where console.log(authors) is called, I noticed that the array seems to be constantly overwriting itself. Typically, in a loop like this, the async part should be outside the loop. To solve the issue of getting an array full ...

The challenge of using CSS Flexbox to position the logo with a margin-top

While learning flexbox, I encountered a challenge. I aim to center align h1, p, and button elements, with the logo positioned at the top margin-top of 1em. Essentially, I want the h1, p, and button to be centered, while the logo is positioned at the top wi ...

The bootstrap down button refuses to function despite having all the necessary files integrated

My bootstrap drop down button isn't functioning correctly even after ensuring all necessary javascript and popper libraries are included as per npm download. <!DOCTYPE html> <html lang="en"> <head> <title>three grid </title ...

What is the best way to extract a list of distinct tags from an HTML document?

Is there a digital tool or basic vanilla Javascript code that can generate a comprehensive list of all the unique HTML tags present in an HTML file? I'm interested in this for the purpose of resetting certain default styles, and I want to ensure that ...

Encountering an error stating that the variable $totalPrice is undefined. I am attempting to display the value of $totalPrice in HTML code using jQuery, but

Undefined variable $totalPrice I encountered an error as I am trying to print $totalPrice in HTML code using jQuery. The code is not working after the success status. function applyCouponCode() { jQuery('#coupon_code_msg&apos ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...

Sending a message to an iframe from a different origin using JavaScript

Just starting out with JavaScript and I'm attempting to send a message to my iframe in order to scroll it. Here is the code I am using: scroll(i) { var src = $("#iframe").attr("src"); $("#iframe").contentWindow.postMe ...

Sending data from local storage to ajax call

Below is the code snippet in question: $.ajax({ url: localStorage.getItem("isntagram link"), // url: "https://api.instagram.com/v1/users/self/feed?access_token=233291163.8a612cd.c49f77de073746e9a2f53116b720302e", met ...

Preventing bootstrap.html or index.html from being included in the history stack using jQuery mobile

I'm currently developing a mobile application using jQuery mobile and PhoneGap. Upon launching the app, a dynamic frontpage is loaded based on certain conditions, such as whether the app has been configured or not. To handle this, I have created a b ...

`The background video is not being displayed on the transparent PNG`

I have created a transparent PNG image featuring a theater setup and I am attempting to overlay a 1-second video as a background element, similar to a GIF. However, when I try to display the video, instead of seeing it, the background color appears. Additi ...

Can Typescript classes be hoisted if I use two classes in my code?

Exploring Class Definitions Certain Rules to Comply With Ensuring that the class is defined in advance helps avoid errors. class Polygon { log() { console.log('i am polygon'); } } const p = new Polygon(); // Expected: no errors p.log(); U ...

Does jQuery have any pre-built validation for LinkedIn profile URLs?

After researching, I discovered that there are suggestions to use regex or a custom function for validating LinkedIn profile URLs in jQuery. I wonder if there is a built-in function available, similar to email validation methods? For instance, consider t ...