Leveraging the local variables within a function in conjunction with the setTimeout method

Currently, I'm facing an issue with a website that I'm working on. I have created a function that should add a specific class to different ids in order to make images fade out one by one on the home page. To streamline the process, I used a local variable 'a' to easily code for the different ids without having to create separate functions. However, I'm running into difficulties when using setTimeout. It seems that I can't get setTimeout to work properly. Any assistance with this matter would be greatly appreciated. The classes are being added to the ids successfully; my struggle lies with the setTimeout function. I've tried various methods that I found online, but I'm having trouble grasping them. Below is the code snippet:

window.onload;

var fetchOne =document.getElementById('picOne');
console.log(fetchOne);

var fetchTwo =document.getElementById('picTwo');
var fetchThree =document.getElementById('picThree');

function AttachClass (a){
    
    a.className ='opacity';
    
}

setTimeout(AttachClass.bind(null,a),8000);

AttachClass (fetchOne);

AttachClass (fetchTwo);

AttachClass (fetchThree);
#picOne{
    
    opacity: 1;
    
    transition: opacity 2s ease-in-out
    
}

#picOne.opacity{
    opacity: 0;
}

#picTwo{
    opacity: 1;
    z-index: -1;
    transition: opacity 2s ease-in-out
    
}

#picTwo.opacity{
    opacity: 0;
}

#picThree{
   opacity: 1;
    z-index: -2;
    
    transition: opacity 2s ease-in-out
}

#picThree.opacity{
    opacity: 0;
}
<div class="landscape_pics">
        
        <img id="picOne" src="media/Photographs/BK3U8791.JPG">
        <img id="picTwo" src="media/Photographs/2014Feb%20-%20Vacation%20-%20Sao%20Paulo%20-%200071a.jpg">
        <img id="picThree" src="media/Photographs/2014Aug06%20-%20Stadium%20-%20001.JPG">
        
    </div>

Answer №1

By setting up one handler for each image with a specific timeout, you can ensure that they fade out independently. However, the code provided lacks the definition of variable a, which renders the setTimeout function ineffective.

To address this issue, you should create separate setTimeout functions for each image that needs to fade out:

for (var i = 0; i < images.length; i++) {
    setTimeout(AttachClass.bind(null, images[i]), 2000);
}

Additionally, the presence of window.onload in the code appears unnecessary and can be removed safely. Once the timeouts are set up, there is no need to call the AttachClass function again.

All you need to do is gather the queried DOM images into an array named

images</code, like so:</p>

<pre><code>var fetchOne = document.getElementById('picOne');
var fetchTwo = document.getElementById('picTwo');
var fetchThree = document.getElementById('picThree');

function AttachClass(a) {
    a.classList.add('opacity'); // IE10+ support only
};

let images = [fetchOne, fetchTwo, fetchThree];

for (var i = 0; i < images.length; i++) {
  setTimeout(AttachClass.bind(null, images[i]), 5000);
}

To further enhance the code, consider applying a common class (e.g., pic) to all images, querying the DOM based on this class, and then setting up the required timeouts:

var images = document.getElementsByClassName('pic');

function AttachClass(a) {
  a.classList.add('opacity'); 
}

for (var i = 0; i < images.length; i++) {
  setTimeout(AttachClass.bind(null, images[i]), 1000);
}

Feel free to experiment with the code using this JSBIN link. Happy coding!

Answer №2

Perhaps you are in need of a solution similar to this:

window.onload = function() {

  ApplyEffect();

  function ApplyEffect() {
    setTimeout(function() {
      var image = document.querySelector('.pics img:not(.opacity)');
      if (image) {
        image.className = 'opacity';
        ApplyEffect();
      }
    }, 1200);
  }
}
.pics img {
  width: 100px;
  opacity: 1;
  transition: opacity 1s ease-in-out
}

img.opacity {
  opacity: 0;
}
<div class="pics">
  <img src="https://pbs.twimg.com/profile_images/843090368837042176/Nl-rCb9c_400x400.jpg">
  <img src="https://pbs.twimg.com/profile_images/843090368837042176/Nl-rCb9c_400x400.jpg">
  <img src="https://pbs.twimg.com/profile_images/843090368837042176/Nl-rCb9c_400x400.jpg">
</div>

Answer №3

Thank you to everyone who assisted me in finding the solution to my problem. Here is how I successfully resolved the issue:

window.onload
var fetchOne =document.getElementById('picOne');
console.log(fetchOne);
var fetchTwo =document.getElementById('picTwo');
var fetchThree =document.getElementById('picThree');



setInterval(function() {
    
    setTimeout(function AttachClass1 (){ fetchOne.className ='opacity';},1000);
    
    setTimeout(function AttachClass2 (){ fetchTwo.className ='opacity';},8000);
        
    setTimeout(function AttachClass3 (){ fetchThree.className ='opacity';},14000);
    
    setTimeout(function RemoveClass2 () { fetchTwo.classList.remove("opacity");},14000)
    
    setTimeout(function RemoveClass1 () { fetchOne.classList.remove("opacity");},18000)
    
    setTimeout(function RemoveClass3 () { fetchThree.classList.remove("opacity");},18000)
    
},24000);

The images now transition one by one as desired, and revert back using the classlist.remove property. I have full control over the intervals which is great. While I am not versed in JQuery yet, I prefer sticking to javascript for now as it's what I am most comfortable with. Once again, thank you all for your assistance!

Answer №4

Here is the code snippet for fading images using JavaScript and CSS:

 var imgs = document.querySelectorAll('.fade');
    var delay = 500;
    for (var i = 0; i < imgs.length; i++) {
        (function(i){
        setTimeout(function () {
            imgs[i].classList.add('opacity');
        }, delay * (i + 1))
        })(i)
    }
.fade {
opacity:.2;
transition: 1s all ease-in-out;
}

.fade.opacity {
opacity:1
}
<div>
    <img src="http://lorempixel.com/200/150/people/" alt="" class="fade" id="i1">
</div>
<div>
    <img src="http://lorempixel.com/200/150/food/" alt="" class="fade" id="i2">
</div>
<div>
    <img src="http://lorempixel.com/200/150/sports/" alt="" class="fade" id="i3">
</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

Experiencing disconnection from SQL server while utilizing the Express.js API

Im currently working on an API that retrieves data from one database and posts it to another database, both located on the same server. However, I am facing issues with the connections. Initially, everything works fine when I run the app for the first time ...

Setting up event listeners from a string array (using PIXI.js)

Hey there! I've encountered a bit of an interesting challenge that could easily be resolved by duplicating the code, but where's the fun in that? This project is more of an experiment for me, just to prove that I can do it. However, the idea has ...

React.js - "Encountered error: Unable to access 'map' property of undefined variable"

I've tried various methods I found through searching, but none of them seem to be working. Why is it still showing that map is undefined? import TextField from '@material-ui/core/TextField'; import Autocomplete from '@material-ui/lab/A ...

The custom created THREE.Curve is not rendering correctly

Following advice from this solution, I have implemented a linearly interpolated curve in the code below: THREE.Linear3 = THREE.Curve.create( function ( points, label /* array of Vector3 */) { this.points = (points == undefined) ? [] : points; ...

Tips for specifying the "url" parameter in xmlhttp.open() for utilizing Ajax in communication with node.js

server.js has the ability to generate a random number. I am trying to retrieve a random number from the server and utilize xmlhttp to send a request. However, the string value remains unchanged when I visit http://localhost:3000/index.html. What could be c ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

What is the best method to ensure that an image remains at the bottom of a div even as the div's height adjusts?

In my current project, I am facing a challenge with positioning an image in the bottom-right corner of a dynamically changing div. Initially, this is easily achieved by using CSS selectors: #div1 { position: relative; } #div1 img { position: abso ...

Complete Guide to Node.JS CRUD Delete Functionality

Currently, I am developing a node.js CRUD application that interacts with MongoDB. The main features of this app are allowing users to upload photos, edit details related to the photos, and delete them from the database. However, I am facing challenges i ...

What is the best method for choosing a div element using JavaScript and altering its background color?

On my website, I have a pop-up modal with a form that contains 5 divs, each with a picture and description. I came across this JS code on w3schools that allows me to style a selected div. However, when the modal is opened, one of the divs is already pre-se ...

Enhance the functionality of your website by implementing a zoom feature

I am looking to dynamically change the CSS of a div using jQuery when it is clicked. The challenge I am facing is that there are multiple divs with the same class and I am unable to modify their classes as they are created dynamically using PHP. <div ...

Is there a way to display my current connected clients to a new client using socket.io?

I am currently working on a project involving socket.io. Upon connecting to a new socket, my input username is displayed in the "usersDiv" where all clients are supposed to be listed. However, I've noticed that when I open another tab and input my nam ...

Creating an expo apk using eas buildWould you like a tool for generating

Following an update to Expo, the process of building apk files using expo build:android -t apk is no longer supported. Instead, it now recommends using eas builds with the command eas build -p android --profile preview. However, this resulted in building a ...

React Bootstrap always displays tooltips

I have integrated react-bootstrap into my project. I am currently attempting to keep a tooltip always displayed, but I am facing some challenges in achieving this. Below are the approaches I have tried so far: <Card style={{width: '10rem'}} ...

Getting the content of a textarea within a v-for loop collection

Exploring this particular situation In a .vue file within the template <div v-for="(tweet, index) in tweets"> <div class="each_tweet"> <textarea v-on:keyup="typing(index)" placeholder="Share your thoughts">{{ tweet.c ...

A guide on showcasing a MultiPolygon GeoJSON on a Leaflet map

I am attempting to showcase a GeoJSON MultiPolygon object on a Leaflet map. I retrieve it from a PostgreSQL database as JSON and transform it into GeoJSON. I have validated the MultiPolygon object on GeoJSONLint and it checks out: However, I am facing di ...

Using jQuery to manage multiple page requests on a single page

In my current project using Codeigniter, I encountered a challenge of loading multiple paginations on one page. After exploring various forums and websites, I decided to implement multiple methods and views to achieve this using jQuery. The code snippet I ...

Why is AJAX failing to execute PHP file from JavaScript?

The Issue: Hello, I have confirmed that my PHP file is functioning properly. However, the AJAX code connected to my JavaScript function seems to be malfunctioning. Even though the function is triggered, nothing happens as expected. The Script: Check o ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...

Move the DIV element to a static section within the DOM

In my Vue app, I have implemented methods to dynamically move a DIV called 'toolbox' to different sections of the DOM. Currently, the DIV is positioned on the bottom right of the screen and remains static even when scrolling. My goal is to use t ...

"Enhance input functionality by updating the value of the text input or resizing the textbox

I've been facing a challenge with updating the value of my input type=text or textbox control text value using jQuery $(window).resize(function(){});. I am aware that the event is triggered because an alert pops up when I resize the browser. Additiona ...