JS method for gradually reducing the opacity of various div elements

I currently have two divs with background images styled using CSS. My goal is to create a loop that fades them in and out continuously.

While attempting to achieve this effect, I encountered some issues and the following code snippet doesn't seem to work as intended.

$(window).load(function(){
var divs = $('.fade');


function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;
    
    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }
    
    var next = divs.eq(nextIndex);
    
    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });
    
    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();
#one {
   background-image: url("Test_bg.jpg");
margin-top: -150px;
min-height: 100%;
background-attachment: fixed;
}

#two {
   background-image: url("Test_bg1.jpg");
margin-top: -150px;
min-height: 100%;
display: block;
background-attachment: fixed;
}
<div id="one" class="fade current">
</div>
    <div id="two" class="fade">
</div>

Answer №1

It appears that you are missing the ending }), which is causing a syntax error.

$(window).load(function(){
            var divs = $('.fade');
            
            
            function fade() {
                var current = $('.current');
                var currentIndex = divs.index(current),
                    nextIndex = currentIndex + 1;
            
                if (nextIndex >= divs.length) {
                    nextIndex = 0;
                }
            
                var next = divs.eq(nextIndex);
            
                next.stop().fadeIn(2000, function() {
                    $(this).addClass('current');
                });
            
                current.stop().fadeOut(2000, function() {
                    $(this).removeClass('current');
                    setTimeout(fade, 2500);
                });
            }
            
            fade();
        })
#one {
          color: red
        }

        #two {
          color: blue
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" class="fade current">a
</div>
<div id="two" class="fade">b
</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

Is it possible to use CSS to swap out main menu items for submenu items?

I have created a basic vertical menu that looks like this: Home Information Info I am wondering if it is possible to replace a list item with its own sublist when the item is active. Specifically, I want to change Home to Sub1 and Sub2 when the item is ...

Switch out the icons within a return statement in JavaScript

Help! I have 5 empty star icons (<StarBorderIcon/>) displayed for a product on the material-ui website. I need to replace them with filled star icons (<StarIcon/>) based on the rating entered into a function. I attempted to use replace(), but i ...

Having trouble getting the Div to fade in on Page load after a 2 second delay?

I am currently facing an issue with a div element that I am trying to make fade in after a 2-second delay upon page load using JavaScript/jQuery. Unfortunately, my attempts have been unsuccessful as the div does not fade in at all. Could someone please as ...

Get around operator precedence in JavaScript

Imagine having a string like this: '1 + 2 + 3 * 4' Can you solve it sequentially from left to right in order to obtain a total of 24, instead of 15? It's important to note that the string is unknown beforehand, so it could be as simple as ...

Creating components in reactjs using the render function

Just a quick query – I've been diving into react js recently. Typically, when we create a component in React, we include the HTML template within the render function. I've noticed that most examples consist of small components with minimal HTM ...

I noticed that my CSS style sheet is only working on three of my pages. What should I do to make sure it affects the fourth page as well?

I am currently facing an issue with my website where I have linked one .css stylesheet to 3 different pages. This is just a temporary template until I finalize the individual look of each page. After performing some div positioning on the site, most pages ...

What is the best way to retrieve the href and id values dynamically from a card in React JS?

Hello everyone, I'm new to stackoverflow and still in the process of learning how to code. Please bear with me if this question sounds like a newbie one. My question is about having dynamic values for href and id when mapping data using axios to crea ...

The Array map function is not displaying the list within a React component that is based on a Class

I am having trouble displaying a list of food items in my Parent component FoodBox.js and its child component FoodItems.js. I am using the map() method, but the <ul> element is showing up empty. Here is my code for FoodBox.js const FOOD_ITEMS = [ { ...

How can we effectively override the automatic contrasting color determination of buttons based on their background in Boostrap v5.2 SCSS compilation?

Buttons in Bootstrap v5.2 dynamically adjust the text color based on the button color. Currently, I am modifying the bootstrap variables override file to change the primary color for my custom theme $green: #369d6d !default; $primary: $green !default; Ho ...

Capturing the clicked element within a Vue (JS) instance by utilizing $(this) can be achieved by following these

I'm currently revamping an older application of mine and running into challenges with DOM manipulation and basic selections within a Vue instance. The data in my database is loaded via AJAX and each record consists of two parts: the header tab (title ...

Multiple instances of Ajax drop-down effects are now available

On my website's staff page, I have implemented a dropdown menu using AJAX to display information about each member of the staff. The issue arises when attempting to open multiple dropdown menus on the same page - the second dropdown that is opened ten ...

Can jQuery be set up to initiate AJAX requests for URLs that have gzip/deflate compression enabled?

I need to utilize a web service that can output data in either gzip or deflated format. My testing has confirmed that this service is capable of responding with raw JSON or gzipped JSON when accessed using wget and curl. My goal is to access this web serv ...

Angular ng-show does not seem to evaluate properly

After receiving the JSON array object below: "Tools": [ { "name": "Submit a Claim", "position": 1, "isOn": true, "alert": null }, { "name": "My Recurring Claims", "position": 2, "isOn": true, "alert": null }, { "name": "Online Enrollment ...

Rect cannot be resized using mouse events

I am currently working on resizing the rectangle inside the SVG using mouse events. To achieve this, I have created another circle shape at the right bottom edge of the rectangle and implemented resize events on that shape. However, I'm facing an issu ...

issues with rounded corners not functioning properly within frameset

I'm trying to display rounded corners in IE frameset, is there a way to do this? Check out the example below: index.html: <html> <head><title></title></head> <frameset rows="*,64" style="margin:0; padding: 0;" frame ...

Using Angular route resolve to handle the sessionStorage login status

I have successfully created a login system using Angular JS. Once the user logs in, a session storage variable is set and they are redirected to a dashboard page (which should only be accessible when logged in). $window.sessionStorage["isLoggedIn"] = true ...

Looking for a JavaScript snippet to insert the word "Search" into an empty DIV element with the specified id attribute

I am trying to insert the word "Search" into an empty input field with the id "ReportQuery" using JavaScript. Unfortunately, I do not have access to the HTML code directly. How can I achieve this task through coding? Below is the snippet of code that nee ...

ExcelJS fails to include images

Trying to insert an image using exceljs, I encountered an error stating that fs.readFile is not a function when attempting to add the image. Here is the error message displayed in the console.https://i.sstatic.net/58hPS.png Below is the code snippet that ...

Add a delay in jQuery so that when triggered by a click, the element fades out smoothly or instantaneously

Currently, I am working on creating a script for a notification popup. My goal is to have the popup fade out either after a certain number of seconds or when the user clicks on the message. While I have been successful in getting each effect to work indi ...

Efficiently centering content in a grid layout using automatic fit repetition for optimized responsiveness

I've implemented a responsive grid where each item has its own hidden details section that is revealed upon clicking the item. The structure of the HTML/CSS setup is as follows: <div class="grid"> <div class="item"> ...