Looping through images using JQuery

I'm struggling with an image animation and can't quite figure out how to make it work.

<div id="img_loop">
  <img src="img/img1.jpg" alt="image1" />
  <img src="img/img2.jpg" alt="image2" class="hidden" />
  <img src="img/img3.jpg" alt="image3" class="hidden" />
</div>

Both the second and third images have a 'hidden' class which makes them display: none in the CSS.

I want these three images to create a continuous loop, transitioning between each one by toggling the 'hidden' class so that only one is visible at a time.

This is what I've been experimenting with:

$(function(){
  setInterval("updateImage()", 2500);
})

function updateImage() {

  var $active = $('#img_loop img').not('hidden');

  var $next = $active.next();

  $active.fadeTo(1000, 1.0, function(){
    $active.addClass('hidden');
    $next.removeClass('hidden')
  })

}

Thank you for any assistance provided :)

Answer №1

Remember that next() does not cycle back to the first image if the active image is already the last one. To handle this, you must check for this scenario and manually select the first image when necessary.

if($next.length == 0){
    $next = $('#img_loop img').first();
}

Additionally, make sure to set the opacity of the currently shown image to 0 instead of 1 when using fadeTo(). Remember to reset this property as well since fadeTo() directly modifies the element's style attribute.

$next.removeClass('hidden').css("opacity","initial")

Lastly, when using the not() method, pay attention to the correct selector. Instead of excluding elements with the name "hidden", use the class selector ".hidden" to target elements with the class hidden.

var $active = $('#img_loop img').not('.hidden');

Demo

$(function(){
  setInterval("updateImage()", 2500);
})

function updateImage() {

  var $active = $('#img_loop img').not('.hidden');
  var $next = $active.next();
  if($next.length == 0){
     $next = $('#img_loop img').first();
  }
  $active.fadeTo(1000, 0.0, function(){
    $active.addClass('hidden');
    $next.removeClass('hidden').css("opacity","initial")
  })

}
.hidden {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="img_loop">
  <img src="https://placebear.com/g/64/64" alt="image1" />
  <img src="https://placebear.com/g/63/63" alt="image2" class="hidden" />
  <img src="https://placebear.com/g/62/62" alt="image3" class="hidden" />
</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

Retrieve the element's value in relation to a different parent element

[JavaScript] How can I access the value of a textbox related to a button through jQuery? The event is triggered when the .button-action is clicked <td class="dmsInput"> <input type="text" maxlength="4" size="4" class="d"> </td> <td& ...

Troubleshooting React and NodeJs Fetch Problem

I am currently working on retrieving data from my API, which is functioning properly. The API endpoint I am trying to fetch results from is http://localhost:5000/api/continents. {"data":[{"continentId":3,"CName":"Atlantis"},{"continentId":2,"CName":"Devia ...

Switching the color of links when they are focused, without changing it when they are clicked by either a mouse or

Is there a way to change the color of a link only when a user navigates to it using the TAB key and not when they click on it? The simple CSS solution I found was: a:focus { color: red; } However, this also changes the color when the link is activated by ...

Exploring, navigating, and cycling through JSON in Node.js

I'm currently attempting to extract the titles of front page articles from Reddit's RSS feed and running into some issues. Below is the snippet of code I am working with: //var util = require('util'); //var cheerio = require('chee ...

Is there a way to continuously send out this ajax request?

My attempt to use setInterval for sending an AJAX request every 2 seconds is causing the page to crash. It seems like there is something wrong in my code! Check out the code below: var fburl = "http://graph.facebook.com/http://xzenweb.co.uk?callback=?" ...

The Sluggishness of MongoDB Aggregation in Determining Distinct IDs within Retrieved Documents

Not only does my Mongo view return a filtered set of documents to the end user, but it also runs a couple of functions to calculate running totals. Strangely though, while my find() operation is blazingly fast (225ms), this additional aggregation process t ...

Retrieving Data from a JSON Object Using a Specific Key

Received a JSON response similar to the one below { "SNGS": { "$": { "xmlns": "csng", "xmlns:ns2": "http://www.w3.org/1999/xlink" }, "Defec ...

Using client-side navigation within an integrated Shopify application

Seeking assistance in implementing client-side routing with react-router within a Shopify app that is embedded. Following the guidelines provided by Shopify on this page, but unsure about what needs to be included in a ./Routes file. Attempted to find rela ...

Avoiding the utilization of automatically generated JSON files as a data source in Rails when

I have implemented javascript code that uses JSON to generate a timeline. The JSON is being created using json_builder and it contains only the current user's information. The JSON displays correctly when accessed directly through its URL, but when th ...

Unable to execute jQuery function from JavaScript

I have been researching this issue and while I found similar posts, none of the solutions seem to work for me. My situation is slightly different. Within my code, I have a javascript function called addFormField that creates a dynamic input element within ...

What is the significance of Fawn's statement, "Invalid Condition"?

Despite following the instructions and initiating Fawn as stated in the document, I'm still encountering an error message that says Invalid Condition. Can anyone help me identify what is causing this issue? Thank you to all the helpers. await new Fawn ...

Challenges arise when creating a complementary php script for a natural language form

I'm a beginner at this and all the PHP I've tried hasn't been successful. I've come across examples of Natural Language forms, but none with functional PHP. While I am familiar with PHP in traditional forms, integrating the two has been ...

What is the best way to customize the appearance of a form element within an angular-schema-form schema without affecting the overall

Currently, I am in the process of constructing a form using the incredible angular-schema-form. Creating the form schema object has been a success so far. My goal is to configure all the form components within the schema using the x-schema-form property in ...

Manipulating URL strings with jQuery

Here are two different scenarios to consider: /abc/qsc/rs#AS626 #AS626 The URLs on the page are generated dynamically. Sometimes the full URL is needed as shown in point 1, while in other cases only the hash is required as shown in point 2. For instanc ...

The Child component is unable to render initially due to the Context API being undefined during the first render of the Child component

I'm struggling to ensure that a child component only renders when the Context API state I've set up is fully mounted. The Parent component fetches data from the server and sets the state based on the received information. Initially, I keep gettin ...

Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

Run a chunk of HTML with dynamic PHP elements using JavaScript

Within a single .php file, there is a combination of HTML, PHP, and JavaScript. The JavaScript section is crucial for detecting the browser; if the browser is not Internet Explorer, JavaScript will trigger the HTML block containing PHP. Here is the JavaS ...

The images on my website are not displaying properly on different devices

My attempt at creating a website for fun and testing purposes is facing issues when viewed on mobile devices. The images and specially positioned elements are not displaying correctly, extending beyond the page boundaries. I have tried adding the viewport ...

What is the best way to retrieve data from Firebase and then navigate to a different page?

I am facing an issue with my app where I have a function that retrieves data from Firebase. However, after the completion of this Firebase function, I need to redirect it to another page. The problem is that when I press the button, the redirection happe ...