Animating the opacity of elements using jQuery and CSS

Trying to put together a fading slideshow with five slides that will loop back to the beginning.

My code seems like it should do the trick, but there's something not quite right.

<script type="text/javascript">

    $(document).ready(function() {

        function playslide(){

            setTimeout(function(){
            $("#slide-two").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 10000);
            setTimeout(function(){
            $("#slide-three").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 20000);
            setTimeout(function(){
            $("#slide-four").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 30000);
            setTimeout(function(){
            $("#slide-five").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 2000, 'swing')}, 40000);

        }

        playslide();

        });
</script>

The concept is that the first slide always stays visible with an opacity of 1, creating a seamless loop. Each slide will show for 10 seconds before fading out and resetting for the next round.

Hopefully, I'm just missing a small detail. Sorry if it's obvious...

Answer №1

Is it possible to use .fadeIn() and .fadeOut() instead in this scenario?

setTimeout(function () {
  $("#slide-two").fadeIn(400, function () {
    setTimeout(function () {
      $("#slide-two").fadeOut(function () {
      $("#slide-three").fadeIn(400, function () {
        // And so forth...
      });
    }, 1000);
  });
}, 1000);

It might be more efficient to utilize these functions for the animation rather than manually adjusting the opacity.

Answer №2

https://jsfiddle.net/sk8ruo3u/

Here is my approach:

var elements = ['.one','.two','.three','.four'];

$.each(elements, function(index, value){
    fadeElement(value, index*1000);    
});

function fadeElement(target, delay) {
    setTimeout(function () {
        $(target).animate({
            opacity: 0.05
        }, 1000);
    }, delay);
};

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

What is the best way to apply a class to an element in an input template using Angular's ngFocus directive, or any directive incorporated in the Ionic Framework?

I'm working with a template that looks like this: <label class="item item-input" ng-class="{'focus':authData.username.focus}"> <--add class here if input:focus <span class="input-label">Username</spa ...

The HTTP response object in Express does not provide any data in its return

While working on developing a server using express js, I encountered an issue. When I send a get request to my endpoint from another server, the response is received successfully; however, it does not contain the data that was sent by the server after res. ...

Retrieve data in devextreme using the $ajax method

Here is the code snippet from my Devextreme script: UmbrellaMobile.Customer = function (params) { var baseAddress = 'http://localhost/Service/GetCustomers'; var Customers Customers = function getCustomers() { $.ajax({ url: baseAddr ...

Finding the correlation between SVG element IDs and JSON keysUnderstanding how to pair up

Currently, I have an SVG file that can be viewed here. My goal is to present specific data when elements within the SVG are clicked. The data is in JSON format and I am looking to match each ID of an SVG element with a key in the JSON data. If both the key ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

Recursive rendering of tree components in React

I am facing a challenge in rendering tree items recursively using React. I have been struggling to achieve the desired outcome as calling treeRender(children) seems to alter the data structure when a folder is encountered for the first time. I am curious a ...

Interested in extracting an HTML table from a Form element within a Python Flask application?

So, in my Flask application, I need to retrieve all the content within a table element. <form action="#"> <table > <tr> <th><input type="text" id="txtName"/></th> ...

Is it possible to automatically play a sound clip when the page loads?

Is there a way to automatically play a sound clip when my page loads? Are there any specific JavaScript or jQuery methods I can use for this, as I am developing my page using PHP. ...

jQuery - Execute, Complete, Finished

My challenge lies in validating a field based on two separate database calls - checking if a condition is true or false. To achieve this, I am attempting to chain multiple AJAX calls together using the .when, .then, and .done methods. However, it appears ...

Utilizing version 4 of Bootstrap to create a visually appealing full

I am currently using the latest version of bootstrap, but I have encountered an issue with my sidebar being too short and not reaching full height. You can view the problem here: Is this problem caused by my CSS or is it a bootstrap issue? And how can ...

Dropping and dragging in the Dojo for the nested lists

Within my HTML code, I am using the Dojo drag and drop feature to sort attributes and move them to another section. However, I am having trouble figuring out how to sort the sections themselves. Here is the structure that I have created: <ul accept=" ...

Submitting a form with Multer when the user chooses to upload a file or not

I have integrated multer into my express app for handling form submissions. The issue I am facing is with the optional image upload feature in the form. Users have the choice to add a photo if they want, but they should also be able to submit the form wi ...

The absence of 'www' in the ajax path is causing an error

Apologies for my poor English as I am currently a student. My issue is related to the use of ajax without "www" in the URL. Let me demonstrate. var path = "www.sinemayolu.com"; //Real-time Ajax Search $('.searchtext').keyup(function ...

How can you move away from using the url:port scheme with socket.io?

Recently, I've been delving into node.js and socket.io, but I'm struggling to eliminate the need to type "url:port" in the browser. Instead, I want users to simply enter the URL and have everything load up, similar to my work-in-progress single p ...

Show identical modal form for various database entities

I have numerous entities that adhere to the IEntity interface (in reality, I have around 10 entities). public interface IEntity { short Id { get; set; } string Name { get; set; } } public partial class Part: IEntity { } public partial class Locali ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

"Headers cannot be set once they have been sent to the client... Error handling for unhandled promise rejection

Having trouble with cookies in the header - specifically, encountering an error at line number 30. The error message reads: "Cannot set headers after they are sent to the client." Additionally, there is an UnhandledPromiseRejectionWarning related to a prom ...

Using a data loader with react-router

I am currently working on a react app where I have implemented routes using the new data loaders from react-router-dom import { RouterProvider, createBrowserRouter, createRoutesFromElements, Route } from 'react-router-dom'; import Home fr ...

Sequelize transforms any given date object into a local date representation

When running a query with a data replacement, the date is not set as UTC in the query. Here's the code snippet: let startInterval = moment('2020-12-09').toDate(); db.query(` SELECT kv.kpiId FROM kpiValues kv WHERE kv.insertDate ...

Using JavaScript's Regex to match sentences, while ensuring any full stops within quotes are ignored

Here is the regular expression: (?:(?:Jr|Master|Mr|Ms|Mrs|Dr|Capt|Col|Sgt|Sr|Prof|Rep|Mt|Mount|St|Etc|Eg)\.\s+|["'“(\[]?)(?:\b(?:(?!(?:\S{1,})[.?!]+["']?\s+["']?[A-Z]).)*)(?:(?:(?:Jr|Master|Mr|M ...