Getting the most out of setInterval() - a guide in jQuery

I am currently working on an auto slide feature and could use some guidance with setInterval(). From my understanding, setInterval() is used to repeat functions infinitely, which is exactly what I need for this project. Here is the current layout:

HTML

<div id="container">
<div id="background_top" class="slide"></div>
<div id="slidephoto"></div>
</div>

CSS

#container {
position:absolute;
width:100%;
height:618px;
overflow:hidden;
}
#background_top {
position:absolute;
background-image:url(images/basvurubg.jpg);
background-size:100%;
background-repeat:no-repeat;
width:100%;
height:618px;
z-index:0;
margin-left:100%;
}
#slidephoto {
position:absolute;
background-image:url(images/bgtop2.jpg);
background-size:100%;
background-repeat:no-repeat;
width:100%;
height:618px;
z-index:-1;
left:0%;
}

jQuery

$('.slide').delay(5000).load("index.html", function() {
$('.slide').each( function() {
    if ($(this).offset().left < 0) {
        $(this).css("left", "150%");
    }
});
$(this).animate({
     left: '-100%'
 }, 500);
 $(this).delay(5000).animate({
     left: '100%'
 }, 550);
 $(this).delay(5000).animate({
     left: '-100%'
 }, 500);
 $(this).delay(5000).animate({
     left: '100%'
 }, 550);

 if ($(this).next().size() > 0) {
     $(this).next().animate({
         left: '0%'
     }, 500);
 } else {
     $(this).prevAll().last().animate({
         left: '0%'
     }, 500);
 }
});

Although the code works as intended, I am looking to make this slide last indefinitely. I attempted to loop the animation by copying the existing code snippet and using setInterval(), but it did not yield the desired result:

$(this).animate({
 left: '-100%'
 }, 500);
$(this).delay(5000).animate({
 left: '100%'
}, 550);
$(this).delay(5000).animate({
  left: '-100%'
}, 500);
$(this).delay(5000).animate({
 left: '100%'
}, 550);

I am seeking a solution to prolong the duration of this slide animation endlessly.

Answer №1

I'm presenting two solutions below:

Option 1 (utilizing setInterval):

$('.slide').delay(500).load("index.html", function() {
  var _this = $(this);
  loop(_this);
});

function loop(thisone) {
  var _this = thisone;
  setInterval(function() {
    _this.animate({
      left: '-100%'
    }, 1000);
    _this.delay(1000).animate({
      left: '100%'
    }, 1000);
  }, 3000);
}
#container {
  position: absolute;
  width: 100%;
  height: 618px;
  overflow: hidden;
}

#background_top {
  position: absolute;
  background-image: url(http://placehold.it/200x100);
  background-size: 100%;
  background-repeat: no-repeat;
  width: 100%;
  height: 618px;
  z-index: 0;
  margin-left: 100%;
}

#slidephoto {
  position: absolute;
  background-image: url(http://placehold.it/350x200);
  background-size: 100%;
  background-repeat: no-repeat;
  width: 100%;
  height: 618px;
  z-index: -1;
  left: 0%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  <div id="background_top" class="slide"></div>
  <div id="slidephoto"></div>
</div>

Option 2 (using setTimeout):

$('.slide').delay(500).load("index.html", function() {
  var _this = $(this);
  loop(_this);
});

function loop(thisone) {
  var _this = thisone;
  _this.animate({
    left: '-100%'
  }, 1000);
  _this.delay(1000).animate({
    left: '100%'
  }, 1000);

  setTimeout(function() {
    loop(thisone);
  }, 3000);
}
#container {
  position: absolute;
  width: 100%;
  height: 618px;
  overflow: hidden;
}

#background_top {
  position: absolute;
  background-image: url(http://placehold.it/600x600);
  background-size: 100%;
  background-repeat: no-repeat;
  width: 100%;
  height: 618px;
  z-index: 0;
  margin-left: 100%;
}

#slidephoto {
  position: absolute;
  background-image: url(http://placehold.it/750x750);
  background-size: 100%;
  background-repeat: no-repeat;
  width: 100%;
  height: 618px;
  z-index: -1;
  left: 0%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  <div id="background_top" class="slide"></div>
  <div id="slidephoto"></div>
</div>

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

How come .trim() isn't cooperating with me?

I am encountering an issue with this particular piece of javascript. Every time I attempt to use it, nothing is displayed in my div. Instead, it simply adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL. <h2>What size d ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

Error: Unable to access the 'address' property of a null object

I am a beginner in the realm of react and have encountered an issue with my app, which is a simple e-commerce platform. The problem arises when I try to enter the shipping address during the checkout process, as it throws an error. TypeError: Cannot read ...

Whenever I try to install the PostCSS plugin in Tailwind CSS and run "npm run build," an error always pops up. I've attempted to troubleshoot multiple times without success. Any suggestions on what I should try next?

When using Windows PowerShell, the following commands are executed: cd D:\TailwindCSS cd gs3 npm run build Output [email protected] build D:\TailwindCSS\gs3 postcss ./src/tailwind.css -o ./public/tailwind.css internal/modules/run_m ...

Issue with dropdown-item not triggering on touch input

I am facing an issue with a Bootstrap Dropdown where the touch event is not working. I am trying to sort list items using isotope.js through this dropdown menu. Here is the code snippet: <div class="dropdown"> <button class="btn ...

What changes should I make to my save function in order to handle both saving and editing user information seamlessly?

My goal for the save function is to achieve two tasks: 1. Save user in table - Completed 2. Update user in table - In progress Save function snippet: var buildUser = function () { $('#save').click(function () { var newUser = {}; ...

Exploring modifications in axis for Google charts timeline

Can anyone help me figure out how to set my Google Timeline chart to always display 24 hours on the x-axis? Currently, it automatically changes based on the earliest and latest points, but I want it to consistently show all 24 hours. For example: ...

Looking for assistance with implementing a like button feature on my web application using CodeIgniter and AJAX

I've been developing an app that features a like button on user profiles. However, I seem to have hit a roadblock and can't figure out how to complete it! What am I missing to get it to function properly? Can anyone lend a hand? Utilizing Ajax ...

What is preventing me from using bracket notation with a variable to assign a property to an object?

I am a complete beginner when it comes to Vuex, and I am currently facing an issue with assigning a value to a Vuex state, specifically state.map.status.isReady. To make my code more reusable, I decided to create a function called changeMapStatus(state, k ...

Why is it impossible for me to show the title "individual name:"?

<p id="display1"></p> <p id="display2"></p> var player1= { alias: 'Max Power', skills: ['shooting', 'running'] }; $("#display1").append( "<br/>" + "player alias :" + player1.alia ...

Navigate directly to a specific section on a webpage

Check out these different links: <a class="faq_text_header_jump" href="#general_questions">Questions About General Topics</a><br> <a class="faq_text_header_jump" href="how_to_use_platform">How to Use the Platform</a><br ...

How to Handle Jquery POST Data in Express Servers

Update Make sure to check out the approved solution provided below. I ended up fixing the issue by removing the line contentType: 'appliction/json', from my POST request. I'm facing a problem trying to send a string to Node.js/Express becau ...

Remove input fields that were generated upon clicking a button

I'm facing an issue with my code that allows me to add inputs using @click="addInput()". However, I am struggling to delete specific inputs using @click="deleteInput(). When I try to delete an input with this.inputs.splice(index, 1), on ...

Handling Removal of Selected Option in React Material-UI Autocomplete Single Selection

I am currently using material UI autocomplete to create a single-select dropdown. However, I have encountered an issue wherein the onChange event does not get triggered when I click the close button on the right side of the input. This prevents my state fr ...

Using jQuery to retrieve the value of a span element involves a few simple steps

Recently, I have started venturing into the world of jQuery. I have managed to create a form field with text input and included some text within a span element. <div class="input-group" style="width:40%"> <input type="text" name="emial" id= " ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

The clash of names between tags and classes in Tumblr themes can cause conflicts

I have discovered a method to customize the style of different posts based on their respective "#tags" using {TagsAsClasses}: <div class="post {TagsAsClasses}"> div.tag { /* customize styling here */ } While this approach works well, I encount ...

Customize CSS class in ASP.Net

Here's the CSS code I am currently using: LinkButton:hover { color:White; background-color:Gray; } .myClass { color:Blue; } The issue I'm facing is that I have a LinkButton with the CssClass .myClass, and when I hover over it, the b ...

Unable to execute JavaScript function by clicking

I've tried everything, but I can't seem to change the button text when selecting an item in the "Requirements" dropdown. You can view the issue on this site. Located at the bottom of the page is the "Requirements" dropdown. Each item has an oncl ...

Encountered a permission denial error (101) while attempting to upload a file to an SFTP server using SSH2 in

Encountering a permission denied error when attempting to upload a file to an SFTP server, whereas the same operation succeeds when using FileZilla. const UploadFiletoFTP = () => { let Client = require('ssh2').Client; var connSetti ...