Creating a perpetual loop animation for two divs moving from right to left endlessly

Here is the code I have:

HTML

<div class="screen screen1"></div>
<div class="screen screen2"></div>

CSS

.screen{
    width: 100%;
    height: 50%;
    position: absolute;
    background-color:#001;
    background-image: radial-gradient(white 15%, transparent 16%),
    radial-gradient(white 15%, transparent 16%);
    background-size:60px 60px;
    background-position: 0 0, 30px 30px;
}

.screen2{
    left: 100%;
}

JavaScript

$(document).ready(function(){
    screen1 = $('.screen1');
    screen2 = $('.screen2');

    move(screen1, screen2);
});

function move(first, second){
    first.animate({left: '-100%'}, 3000, function(){
        first.css('left', '100%');
        move(second, first);
    });
    second.animate({left: 0}, 3000);
}

I am trying to create an infinite repeating background animation with two divs using jQuery. The animation works well, but there is a small pause when moving .screen1 to the right.

Here is the link to the fiddle:

https://jsfiddle.net/mavisme/a1275tuv/

How can I fix this pause and make the animation run smoothly?

Answer №1

If you're looking to enhance your design, consider exploring CSS animations as an alternative to jQuery:

@keyframes animate {
  from {
    background-position: 0 0;
  }
  to {
    background-position: -60px 0;
  }
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

html, body {
  height: 100%;
  min-height: 100%;
  overflow: hidden;
}

.screen {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: #001;
  background-image: radial-gradient(white 15%, transparent 16%), radial-gradient(white 15%, transparent 16%);
  background-size: 60px 60px;
  animation: animate 300ms linear infinite;
}
<div class="screen"></div>

Answer №2

If you're finding the "speeding up" and "slowing down" at the start and end of each cycle to be unsatisfactory, consider looking into 'easing':

function move(first, second) {
    first.animate({
        left: '-100%',
    }, 3000, 'linear', function() {
        first.css('left', '100%');
        move(second, first);
    });
    second.animate({
        left: 0
    }, 3000, 'linear');
}

easing (default: swing)

You can specify a string indicating which easing function to use for the transition.

Check out this link for more information on jQuery's animate method.

Answer №3

Creating a continuous loop animation for two divs moving from right to left

This is the code I used:

https://jsfiddle.net/abc123xy/7/

 $(function(){
        var position = 0;
        setInterval(function(){
            position -= 1;
            $('.panel').css('background-position', position + 'px 0');
        }, 10);
    })

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

What kind of error should be expected in a Next.js API route handler?

Recently, I encountered an issue with my API route handler: import { NextRequest, NextResponse } from "next/server"; import dbConnect from "@/lib/dbConnect"; import User from "@/models/User"; interface ErrorMessage { mess ...

Using Linux variables in the .env file of your Vue.js project can provide a convenient way to

Using .env in a *.js file allowed me to set the BANK variable as either A_BANK or B_BANK like so: BANK=A_BANK or BANK=B_BANK However, when passing the argument as A_BANK or B_BANK like: --bank A_BANK in a shell script loop for var in $@ do if [ ${var} ...

What is the best way to incorporate a Django variable as the width parameter in a style tag within HTML?

I'm attempting to utilize a Django variable as the percentage width value within a style tag in HTML, but it's not functioning correctly. Strangely, I've discovered that using curly braces {} within style tags is prohibited—this contradict ...

Preserve file sequence with jquery file upload

I recently came across an interesting upload script at the following link: This script utilizes jquery file upload to allow for uploading multiple files simultaneously. I'm curious about how to transmit the order in which the files were selected to t ...

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...

It appears that the Next.js environment variables are not defined

Upon setting up a fresh next.js project using npx create-next-app@latest and configuring some environment variables in the .env.local file, I encountered an error when attempting to run the server. "Failed to load env from .env.local TypeError: Cannot ...

How to retrieve headers using Express.js middleware

My middleware creates authentication API keys that are then added to the header. const loger = require("easy-loger"); require('dotenv').config(); function authMiddleware(req, res, next){ const appApiKey = process.env.API_KEY; l ...

"Enhance User Experience with Multilevel Dropdowns in Bootstrap 4 - Submenus Aligned to the Top

I recently embarked on a project that involved using Bootstrap 4.4, The project is an eCommerce grocery store with departments comprising categories and subcategories. The main menu became very lengthy when using the default code, so I encountered some al ...

What is the best way to determine if a child div exists within a parent div?

Is there a way to determine if any div exists within the parent div? In my current scenario, I am adding two divs inside the parent div like this. $('#realTimeContents').append("<div style='width:22%; float: left; font-size:18px; line- ...

Press on the menu <li> item to create additional submenus

A group of friends is facing a challenge. They want to create a dropdown sub-menu that appears directly below the selected item when clicking on a link from a menu. So far, they have been able to use ajax to send requests and generate a sub-menu. However, ...

Contrast and combine information from two JavaScript arrays of objects

I am struggling with comparing two arrays of objects based on a key. My goal is to compare the values, subtracting them when the keys match and displaying negative values for those not found in my target array. Additionally, I want to include all target o ...

Prevent global backorders for products in WooCommerce, including within the admin settings

I am curious about how to globally disable backorders in WooCommerce. I came across some helpful resources: How to disable globally backorders in WooCommerce Currently, I am using add_filter( 'woocommerce_product_backorders_allowed', '__re ...

Update dataTable with new data fetched through an ajax call from a separate function defined in a different

I need to refresh the data in my datatable after using a function to delete an item. The function for deleting is stored in a separate file from the datatable. Here is the delete function code: function removeFunction(table,id) { var txt= $('.ti ...

I'm looking to extract various data from a SQLite table using the URL with ExpressJS. What's the best way to achieve

I need to access data from a SQLite database table that contains information on accounts, movies, and reviews. Specifically, the structure of the reviews-table is as follows: CREATE TABLE IF NOT EXISTS reviews ( id INTEGER PRIMARY KEY, authorId INT ...

Is it normal for the protractor cucumber tests to pass without observing any browser interactions taking place?

Having recently started using protractor cucumber, I have created the following feature. Upon launching protractor protractor.conf.js, the browser opens and immediately closes, displaying that my tests have passed. Is this the expected testing behavior? Sh ...

Instructions for adding the more-vert icon from material-ui into a react project

I've been searching tirelessly, but I can't seem to locate it. Where exactly is the location of this in material-ui? I've seen others using it. Any assistance would be greatly appreciated. My initial thought was: import MoreVertIcon from & ...

Restrict the size of the numerical input in AngularJS

<input class="span10" type="number" max="99999" ng-maxLength="5" placeholder="Enter Points" ng-change="myFunc($index)" ng-model="myVar"> This code snippet adjusts the value of form.input.$valid to false if the number entered exceeds 99999 or is long ...

Why does jQuery's .not(this) still identify the current row selected?

I have a table populated with data, each row ending in an icon marked with the "icon-size" and "edit" classes. I am trying to implement a feature where a selected row is highlighted with special emphasis borders. However, I am facing issues with toggling t ...

Easy way to eliminate empty elements following a class using jQuery

I'm encountering a situation where I have a group of elements following a specific class that are either empty or contain only white space. <div class="post-content"> <div class="slider-1-smart"> --- slider contents --- < ...

Adjust the color of additional SVG paths upon hovering

I have the following code snippet. .icon {stroke-width: 0; stroke: currentColor; fill: currentColor;} a {color: red} a:hover {color: pink} a:hover circle {fill: green !important; color: orange} a:hover path {fill: blue !important} <a href=""> ...