Is there a way to continuously run jQuery code or reset it?

Can you help me create a loop that will continuously run this script after it finishes executing, repeating the process indefinitely?

I want to keep running this code over and over again.

This script is using jQuery version 3.5.1

// Title
    var title1 = document.getElementById("slide-text-title-id");
    var title2 = document.getElementById("slide-text-title-id-2");
    var title3 = document.getElementById("slide-text-title-id-3");

        $(document).ready(function () {
            setTimeout(function () {
                $(title1).css("opacity", "1");
                $(title1).css("transition", "0.5s");
            }, 500);
            setTimeout(function () {
                $(title1).css("opacity", "0");
            }, 6000);
            setTimeout(function () {
                $(title1).css("opacity", "1");
            }, 20000);
        });

        $(document).ready(function () {
            setTimeout(function () {
                $(title2).css("opacity", "1");
                $(title2).css("transition", "0.5s");
            }, 9000);
            setTimeout(function () {
                $(title2).css("opacity", "0");
            }, 13500);
            setTimeout(function () {
                $(title2).css("opacity", "1");
            }, 20000);
        });

        $(document).ready(function () {
            setTimeout(function () {
                $(title3).css("opacity", "1");
                $(title3).css("transition", "0.5s");
            }, 16000);
            setTimeout(function () {
                $(title3).css("opacity", "0");
            }, 21000);
            setTimeout(function () {
                $(title3).css("opacity", "1");
            }, 26500);
        });

Answer №1

The fundamental concept:

// the array of elements:
const elements = ['a', 'b', 'c'];

// the stepper function (also known as walker or iterator)
function stepper(index) {
  // the current element is elements[index];
  // perform an action with the current element:

  console.log({
    index,
    [`currentElement (elements[${index}])`]: elements[index]
  });

  // after a set time interval (3000ms), call this function again with the next index:
  // when the current element is the last one, we restart from the beginning:

  setTimeout(function() {
    stepper(index + 1 < elements.length ? index + 1 : 0);
  }, 3000);
}

// initiate the loop:
stepper(0);

Now, let's apply this concept to some elements. One way to achieve this is by toggling the class active on a series of slides. By using CSS, we can style the active element. To control the animation direction, I'm also incorporating a leaving class to the currently active slide, which is then removed in the next iteration.

The devil is in the details. Attention to details plays a significant role in web development.

const elements = [1, 2, 3];

function stepper(index) {
  // remove the leaving class from all slides
  $('.slider .leaving').removeClass('leaving');

  // add the leaving class to the previously active item and remove the active class
  $('.slider .active').addClass('leaving').removeClass('active');

  // add the active class to the current item
  $('.slider > div').eq(index).addClass('active');

  setTimeout(() => stepper(index < elements.length - 1 ? index + 1 : 0), 2100);
}

// initiate the infinite loop:

stepper(0);
body {
  margin: 0;
}
.slider {
  position: relative;
  overflow: hidden;
}

.slider > div {
  font-size: 7rem;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  height: 100%;
  width: 100%;
  transform: translateX(100%);
  background-color: #ccc;
  color: white;
}
.slider .leaving {
  transform: translateX(-100%);
  transition: transform .42s cubic-bezier(.4,0,.2,1);
}
.slider .active {
  position: relative;
  opacity: 1;
  transform: translateX(0);
  transition: transform .42s cubic-bezier(.4,0,.2,1)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider">
  <div>Slide 1</div>
  <div>Slide 2</div>
  <div>Slide 3</div>
</div>


Note: I aimed to explain the core concept followed by a basic implementation. Real-world code tends to be more intricate and elaborate. Based on your current approach, I suggest starting with the fundamentals.

One of the most effective ways to learn is by watching tutorials while simultaneously experimenting with the code provided. Don't hesitate to make alterations. Gradually modify every component and observe how it affects the outcome.

At each step, utilize console.log({ stuff }) to inspect the contents of stuff at that precise point.
Break the code. Understanding why it breaks will enhance your comprehension of that segment as well!

Answer №2

using the function setInterval

var interval = setInterval(function ()
{
  // Retrieving elements by id
  var title1 = document.getElementById("slide-text-title-id");
  var title2 = document.getElementById("slide-text-title-id-2");
  var title3 = document.getElementById("slide-text-title-id-3");

  $(document).ready(function () {
      // Setting opacity and transition for title1
      setTimeout(function () {
          $(title1).css("opacity", "1");
          $(title1).css("transition", "0.5s");
      }, 500);
      setTimeout(function () {
          $(title1).css("opacity", "0");
      }, 6000);
      setTimeout(function () {
          $(title1).css("opacity", "1");
      }, 20000);
  });

  $(document).ready(function () {
      // Setting opacity and transition for title2
      setTimeout(function () {
          $(title2).css("opacity", "1");
          $(title2).css("transition", "0.5s");
      }, 9000);
      setTimeout(function () {
          $(title2).css("opacity", "0");
      }, 13500);
      setTimeout(function () {
          $(title2).css("opacity", "1");
      }, 20000);
  });

  $(document).ready(function () {
      // Setting opacity and transition for title3
      setTimeout(function () {
          $(title3).css("opacity", "1");
          $(title3).css("transition", "0.5s");
      }, 16000);
      setTimeout(function () {
          $(title3).css("opacity", "0");
      }, 21000);
      setTimeout(function () {
          $(title3).css("opacity", "1");
      }, 26500);
  });

}, 0);

Alternatively, you can achieve the same using setTimeout

var timer;
!function loop()
{
  // Retrieving elements by id
  var title1 = document.getElementById("slide-text-title-id");
  var title2 = document.getElementById("slide-text-title-id-2");
  var title3 = document.getElementById("slide-text-title-id-3");

  $(document).ready(function () {
      // Setting opacity and transition for title1
      setTimeout(function () {
          $(title1).css("opacity", "1");
          $(title1).css("transition", "0.5s");
      }, 500);
      setTimeout(function () {
          $(title1).css("opacity", "0");
      }, 6000);
      setTimeout(function () {
          $(title1).css("opacity", "1");
      }, 20000);
  });

  $(document).ready(function () {
      // Setting opacity and transition for title2
      setTimeout(function () {
          $(title2).css("opacity", "1");
          $(title2).css("transition", "0.5s");
      }, 9000);
      setTimeout(function () {
          $(title2).css("opacity", "0");
      }, 13500);
      setTimeout(function () {
          $(title2).css("opacity", "1");
      }, 20000);
  });

  $(document).ready(function () {
      // Setting opacity and transition for title3
      setTimeout(function () {
          $(title3).css("opacity", "1");
          $(title3).css("transition", "0.5s");
      }, 16000);
      setTimeout(function () {
          $(title3).css("opacity", "0");
      }, 21000);
      setTimeout(function () {
          $(title3).css("opacity", "1");
      }, 26500);
  });
  timer = setTimeout(loop, 0);
}();

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

Transform JSON array containing identical key-value pairs

My array is structured as follows: [ { "time": "2017-09-14 02:44 AM", "artist": "Sam", "message": "message 1", "days": 0 }, { "time": "2017-09-14 02:44 AM", " ...

Copying the position of one object to another in THREE.js does not function as expected

Recently I started experimenting with Three.js and I’m currently working on a project where I need to position a SpotLight at the same coordinates as the camera. Below is the code snippet I’m using: $(document).ready(function() { init(); }); func ...

Tips for maintaining the order in a JavaScript Map structure

Here is the layout of myData map: var myData = new Object(); myData[10427] = "Description 10427"; myData[10504] = "Description 10504"; myData[10419] = "Description 10419"; However, when I loop through myData, the sequence is not consistent between ...

Clicking on the ng-repeat will trigger the ng-click event, which populates all the data using ng

I need help including an HTML page using ng-click within ng-repeat. However, it is currently loading all the content for every ng-repeat element. My specific requirement is to only bind(ng-include) the clicked element. Please see the attachment for m ...

Encountering TypeError with Next.js and Firebase: Unable to access properties of undefined (specifically 'apps')

My goal is to create an authentication system using NextJS and Firebase. The issue I am facing is in my firebaseClient.js file, where I am encountering the error "TypeError: Cannot read properties of undefined (reading 'apps')". Here is a snipp ...

Sending the selected multiple values to the controller function

I am facing an issue with sending the selected values of a multi-select list to an Action in my Controller. Despite verifying that val() shows an array of selected values like ["33","175"] when printed to the console, the Action's argument always ends ...

Is the treatment of __proto__ different in the fetch API compared to manual assignment?

When using fetch to retrieve a payload containing a __proto__, it seems that the Object prototype is not affected in the same way as when directly assigning to an object. This behavior is beneficial as it ensures that the Object prototype remains unaffect ...

vertically centering a div specifically on laptops

What is the best way to vertically center a div on lap-tops? (...) body {padding: 4% 16%;} body {top:0px; left:0px; bottom:0px; right:0px;} body {border: 12px solid darkred; border-style: double;} body {background-color: #FAFCB4;} p {font-size: 80%; text- ...

eliminating the hues beneath the lines on Morris region charts

I'm seeking advice on how to remove colors below the lines in Morris area charts. Any ideas? Here's the code snippet I've been using: Morris.Area({ element: 'area-example', data: [ { y: '2006', a: 100, b: 90 }, ...

What strategies can be implemented to enhance the performance of this jQuery slider?

I have successfully created an image carousel. https://i.sstatic.net/CbypXxRr.png Encountered Challenges: The last slide is displayed, but the counter shows the first slide. How can I resolve this issue? When clicking play, it continues to advance ...

The Prev and Next controls on the web carousel have mysteriously vanished

I managed to successfully create a carousel in the picture below, but I'm facing an issue where the next button is positioned on the white side of the page. Despite trying to enlarge the carousel's size, it ends up going below the category contai ...

Enhance your website with a dynamic div zoom feature using the Jquery Zoom

I've been scouring the internet for a jQuery plugin that allows me to zoom in on an image. There are many options out there, but I prefer ones that display the zoomed-in image in a separate area rather than directly on the original image. For example ...

Error message: The Bootstrap .dropdown() method failed because it encountered an "Uncaught TypeError: undefined is not a function"

I've encountered an issue that seems to be a bit different from what others have experienced. Despite trying various solutions, I still can't seem to fix it. I suspect it might have something to do with how I'm importing my plugins. The erro ...

Unexplained vanishing of CSS padding upon form submission

Hey there! I've been working on creating a contact form using PhP, HTML, and CSS. Everything seems to be working fine except for one issue - when I submit the form with incorrect information, the CSS padding disappears. Can anyone help me figure out w ...

Load data asynchronously using a promise in select2

Is there a way to load options for select2 asynchronously without using ajax requests? I want to retrieve values from a promise object instead. Currently, my code loads data in the query function, but this means that it queries the data with every keystrok ...

using the newquestion variable later in the function

In the Vue.js code snippet below, there is a variable named newQuestion that is passed to the function getAnswer like this: this.getAnswer(newQuestion). Further down in the methods section, particularly at this line getAnswer: _.debounce(, I would like to ...

Changing Page Content with Ajax Post-Redirect Pattern

Just had a quick question. Can the redirected page be affected by ajax's success function? The code will provide a better explanation. $.ajax({ type: "POST", url: "/admin/done", data: { ...

The React-Chartjs chart is displaying without any color rendering

I attempted to create a radar chart using react-chartjs library, but I am facing an issue where the colors are not appearing when it renders. https://i.stack.imgur.com/tjAsW.png What could be causing this problem? I followed a significant portion of the ...

Node.js local storage/cookie functionality

Running three different apps on Node.js at ports 3000, 3005, and 3007. I need to set a LocalStorage or Cookie variable at port 3000 and access it from the apps running at ports 3005 and 3007. Folder structure: nodep/ |-app.js (runs at port 30 ...

Resource Jump.js could not be loaded

Although I am still new to NPM, I have mostly built websites without using it. Recently, I decided to implement smooth scroll using Jump.js. Initially, everything seemed to work well when I used the live server extension in VScode. However, once I uploade ...