Fade in images using jQuery

I am having issues with fading in and out images using jQuery, it doesn't seem to be working as expected. I think there might be something crucial that I am missing.

Take a look at the script below:

var count = 1;
setInterval(function() {           
    count = (jQuery(".slideshow :nth-child("+count+")").fadeOut().next().length == 0) ? 1 : count+1;
    //alert (count);
    jQuery(".slideshow :nth-child("+count+")").fadeIn();
}, 2000);

Below is the HTML snippet for reference:

<div class="slideshow">
    <div class="hover">
        <a href="#">
            <img src="#" />
            <div class="mainportfo_title">title</div>
        </a> 
    </div>
    <div class="hover">
        <a href="#">
            <img src="#" />
            <div class="mainportfo_title">title</div>
        </a> 
    </div>
</div>

Answer №1

If you're looking to enhance the functionality of this code snippet, consider utilizing JQuery get(). Take a look at the code provided below and see how you can make improvements:

var i = 0;

setInterval(function() {
    var target = $("img").get(i);
    var next = $("img").get(++i);
    $(target).fadeIn( "slow", function() {
        $(target).fadeOut( "slow", function() {
            $(next).fadeIn();
        }); 
    });
    if(i >= $("img").size()) {
        i = 0;
    }
}, 3000);

Answer №2

Would you like to try this out?: Click here for the jsfiddle demo

let counter = 1;
setInterval(function() {
    counter = (jQuery(".slideshow:nth-child("+counter+")").fadeOut().next().length == 0) ? 1 : counter + 1;
    jQuery(".slideshow:nth-child("+counter+")").fadeIn();
}, 2000);

Answer №3

In order to ensure correct selection, it is important to specify your .hover elements when using the .nth-child selector.

let count = 1;
setInterval(function () {
    count = ($(".slideshow .hover:nth-child(" + count + ")").fadeOut().next().length == 0) ? 1 : count + 1;
    console.log(count);
    $(".slideshow .hover:nth-child(" + count + ")").fadeIn();
}, 2000);

Check out the fiddle here!

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

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

The implementation of Typescript in Express does not rely on Middleware

I've encountered an issue with my Auth Middleware - it seems that the middleware isn't being called at all. Even when I intentionally throw an Error within the middleware function, nothing is printed out. For testing purposes, I only need to inv ...

Is it possible to apply border-radius to selections, similar to how it is done in vscode

It was reminiscent of this... Visual Studio Code ::selection{ border-radius: 5px; } I attempted something similar to this, however it was not successful... ...

The form is successfully submitted by Jquery, yet the div does not fade as expected

Hey there! I've been working on a jQuery code that's giving me some trouble. Here's what I have so far: $("#myForm").submit(function(){ //alert($(this).serialize()); $.post("submit.php", $(this).serialize(), functi ...

React component unmounts but listener remains attached

After developing a SPA using react.js, I have incorporated react-router-dom, react-redux, and various other modules. The routes defined in my application: const allRoutes = [ { path: "/Intro", name: "Intro", component: Intro }, ...

Can you tell me the CSS equivalent of the SASS/SCSS expression "&$"?

Hey there! I've been diving into the world of Material-UI components and stumbled upon this interesting styling snippet: root: (0, _extends3.default)({}, theme.typography.subheading, { height: theme.spacing.unit * 3, boxSizing: 'content- ...

Tips for toggling content visibility in jQuery using multiple radio buttons

When a radio button with the value "true" is selected, it should display a corresponding div below it. If "false" is selected, it should hide the div below it. Here is my current attempt: If TRUE is selected, then show the input field. If FALSE is selecte ...

Organizing table components solely using CSS

Can anyone help me center 3 spans in a list within a table? Currently, the alignment looks like this: spans not properly centered. However, I want it to appear like this: span properly centered. ul { text-align: center; list-style-position: inside; ...

Dividing HTML and JavaScript using Vue

Is there a way to separate HTML from data/methods in VueJS to avoid having one long file with both? I tried moving the contents of my <script> section into a new file called "methods.js" and importing it using: <script src="methods.js"> Note ...

Transmitting JSON data to a WebMethod via AJAX

Currently, I am retrieving data from an HTML form and converting it into a JSON object to be sent to a WebMethod. Although the response indicates success, I am unsure about how to verify if it is being correctly transmitted to the WebMethod. I have attemp ...

To successfully process this file type in JavaScript, you might require a suitable loader

Currently, I am facing an issue with my MVC application while trying to integrate Bootstrap 5 using Webpack. Despite attempting various workarounds with stage-0, stage-2, and stage-3, none have proven successful for me. I suspect that the problem lies wit ...

Delete the previously added class that was generated dynamically

I have implemented a snippet that adds a class based on an element's id: $('.block').click(function() { $('#bg').addClass($(this).attr('id')); }); However, there seems to be an issue with previously clicked ...

Access a SQL database to retrieve a data value and seamlessly integrate it into an HTML document with the help of node

I am new to web development and currently facing a challenge in displaying SQL content on an HTML page. My stack includes Node.js, Express, and SQLite3. I have a folder named public containing HTML, CSS, and JS files. The objective is to retrieve a varia ...

Preventing touchstart default behavior in JavaScript on iOS without disrupting scrolling functionality

Currently experimenting with JavaScript and jQuery within a UIWebView on iOS. I've implemented some javascript event handlers to detect a touch-and-hold action in order to display a message when an image is tapped for a certain duration: $(document) ...

Looking for assistance with a JavaScript code snippet

I have encountered an issue while iterating through receipts in the given code snippet. The objective is to fetch the receipt number for each receipt and add it to a JSON object. However, I am facing a problem where the same receipt is appearing in two sep ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

Issue with express-http-proxy where relative URL paths are not functioning as expected

My server is hosting an app along with a few simple web microservices. I want to access these services over the internet without having to open individual ports for each one. To achieve this, I decided to set up a reverse proxy on the server using express- ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

What is the best way to change the font size in HTML?

https://i.sstatic.net/IjLvn.png After carefully analyzing the image provided, I encountered an issue while attempting to incorporate the code display:block. However, no changes were reflected. Can you identify what may be causing this discrepancy in my te ...

A step-by-step guide to showing images in React using a JSON URL array

I successfully transformed a JSON endpoint into a JavaScript array and have iterated through it to extract the required key values. While most of them are text values, one of them is an image that only displays the URL link. I attempted to iterate through ...