Automobile box sliding smoothly in a horizontal motion, gliding gracefully from left to

I currently have three boxes that are functioning as expected. However, I am looking to automate this process to run every 30 seconds without requiring a 'click' event. You can refer to this fiddle http://jsfiddle.net/ykbgT/8493/. Any suggestions on how to achieve this?

The code snippet is provided below

<div id="box1" class="box">Div #1</div>
<div id="box2" class="box">Div #2</div>
<div id="box3" class="box">Div #3</div>

$('.box').click(function () {
    $('.box').each(function () {
        if ($(this).offset().left < 0) {
            $(this).css("left", "150%");
        } else if ($(this).offset().left > $('.box').width()) {
            $(this).animate({
                left: '50%',
            }, 500);
        } else {
            $(this).animate({
                left: '-150%',
            }, 500);
        }
    });
});

Answer №1

If you want to create a continuous loop in JavaScript, you can utilize the setInterval() method.

setInterval() - This function will repeatedly execute a specified function at set time intervals.

Check out this JSFIDDLE DEMO for more information!

setInterval(function(){
    $('.box').each(function() {
        if ($(this).offset().left < 0) {
            $(this).css("left", "150%");
        } else if ($(this).offset().left > $('.box').width()) {
            $(this).animate({
                left: '50%',
            }, 500 );
        } else {
            $(this).animate({
                left: '-150%',
            }, 500 );
        }
    });
}, 30000);

Answer №2

setInterval(function() {
    $('.rectangle').each(function() {
        if ($(this).offset().top < 0) {
            $(this).css("top", "150%");
        } else if ($(this).offset().top > $('.rectangle').height()) {
            $(this).animate({
                top: '50%',
            }, 500);
        } else {
            $(this).animate({
                top: '-150%',
            }, 500);
        }
    });
}, 30000);

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

Unable to set the jQuery UI checkbox as checked or unchecked using values from an AngularJS model

Utilizing jQueryui's checkbox group feature, I have implemented three options for users to select. While I have successfully linked each checkbox to an angular model, I am facing an issue where the checkboxes do not automatically check themselves when ...

Creating a cohesive look with a background gradient and image simultaneously

Short Version Is it possible to have both a background color with a linear gradient and a background image at the same time? Long Version I have styled a table with a vertical linear gradient in the header, as shown below: table { white-space: no ...

Trying out enzyme's componentDidUpdate method in ReactJS testing

I have been attempting to test the componentDidUpdate method, but I am struggling to cover it completely. This is how I am approaching the testing: it('should execute storeCardDesigns if specific conditions are met in componentDidUpdate', () ...

"The changes made to the list are not being accurately displayed by Angular's ng

I am working on a directive that injects dynamic templates during ng-repeat. While I can successfully add items to the list, they do not appear in the view for some reason. It seems like I am missing a crucial piece to make it work correctly. You can find ...

ReactStrap: Issue with displaying an elongated dropdown menu within a table cell

I am facing an issue with a dropdown menu embedded inside a table: https://i.sstatic.net/iOusF.png The dropdown list is quite long with 16 items. However, when I try to scroll down to access the last items, the entire table scrolls down along with the d ...

Issue with scroll being caused by the formatting of the jQuery Knob plugin

I am currently utilizing the jQuery Knob plugin and I am looking to have the displayed value shown in pound sterling format. My goal is for it to appear as £123456. However, when I attempt to add the £ sign using the 'format' hook, it causes is ...

The functionality of Jquery UI is not compatible with version 1.12

Incorporating jQuery UI into my current project has presented some challenges. Both the jquery-ui.min.css and jquery-ui.min.js files are version 1.12, so I opted for the latest jQuery version, jquery-3.2.1.min.js. Specifically, I decided to test the datep ...

Error: Sentry serverless - Unable to access the 'finish' property as it is undefined

Hey there, The sentry service is functioning, but I'm encountering this error message in Amazon CloudWatch: I'm utilizing serverless-webpack to compile my files, and it was working fine in other projects. Does anyone have an idea of what might ...

Building a bridge between React Native and MongoLab

I am currently in the process of developing a React Native application for iOS that will require querying a database. After some research, I have chosen to use MongoLab. Upon reviewing MongoLab's documentation, it is suggested to utilize the MongoDB D ...

How can you organize and save models in Three.js in the order they are loaded/called?

When loading models, I want to ensure they are placed in the object array in the same order as they are called. However, sometimes they get assigned a different number and end up in a different sequence. Is there a way to guarantee that the models are pla ...

Setting up Quill in a Nuxt project (a VUE component)

I'm struggling to remove the toolbar in Quill despite my efforts. This is the HTML snippet I am working with: <template> <quill v-model="content" :config="config"></quill> </template Here's what I have inside the scri ...

Each time a user drags and drops, I aim to save an ID to the localStorage

I am faced with a challenge involving two panels. In the left panel, there are multiple cards each with a unique id assigned to them as an attribute in the div element. When a user performs drag and drop action over to the other panel, I successfully use t ...

Experience working with MySQL, PHP, JSON, and JavaScript

When working with JavaScript that retrieves data from a server’s database and displays it on a webpage, issues can arise. $.getJSON( 'ajax.php',{id:$('bla').val()}, function(json) { $('#myClone').clone().removeAttr(&apo ...

Utilizing Method-Override with a PUT request

Within my app.js file, I included the method-override module and utilized app.use(methodOverride("_method")) However, An issue arose indicating that the error message did not contain the ?_method=PUT parameter in the URL. This snippet is a portion of my ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

How to utilize regular expressions in JavaScript without the need to instantiate a regex object

Here is a code snippet that checks a URL for a specific pattern: var url = "https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regex%20javascript"; var patt = new RegExp('https?:\/\/[^/]+\.google ...

Implement a new list field to an object using javascript

I am facing a challenge in converting a JSON object to a list of JSON objects and then adding it back to JSON. Here is an example: config = { existing_value: 'sample' } addToListing = (field, value, index=0) => { config = { ...confi ...

Troubleshooting Problem with Bootstrap CSS Menu Box Format

I'm having trouble creating a simple menu for my Bootstrap site. What I want to achieve is something like this: https://i.sstatic.net/abZXC.png This is what I have accomplished so far: https://i.sstatic.net/JFVC2.png I've attempted to write th ...

Customize Material-UI Icons styles in React app

I'm working on a React.js app with Typescript and I need to remove the default visited Material Icons coloring from an anchor tag. Here's the stylesheet I tried: const useStyles = makeStyles((theme: Theme) => createStyles( myAnchor: ...

Having trouble getting the height to work properly on your Blogger Blogspot template?

Issue with embed height=100% not working <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr"> <head> & ...