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

Detaching the jQuery event where the context is tied to the handler

My current challenge involves removing a jQuery event with a callback function bound using this. The issue arises from the fact that .bind() generates a new function each time it is called, causing difficulties when trying to remove the event. I am strugg ...

Alter information within jQuery AJAX success function

A sample function is provided below: jQuery.ajax({ type: "POST", url: jQuery("#exam_form").attr( 'action' ), data: jQuery("#exam_form").serialize(), success: function(result){ //Add row table.append(result); ...

Switching the Vue image on Routerlink's isExactActive feature

Is there a way to display different images based on whether a link is active or not? <router-link to="/"> <img src=" :active = isExactActive ? pic_active.png : pic_inactive.png}}" /> //Something along these lines ...

What is the mechanism by which a custom hook, functioning as a trigger, initiates the re-rendering of a separate function component?

According to the official documentation on Custom React Hooks, one particular use case for utilizing a custom hook is demonstrated through the following example: function FriendListItem(props) { const isOnline = useFriendStatus(props.friend.id); retur ...

Check to see if a specific div element is found within a different one

I'm facing a challenge that might seem simple, but I can't figure it out: How can I check if the "comWF" div appears at least once within each "comW" div? For example: <div class="comW"> <div class="comWF"></div> </div& ...

Using default language in Next.js internationalization: a step-by-step guide

I've been immersing myself in the Nextjs internationalization documentation for the past two days. My goal is to have support for two languages: en, fa. I also want to be able to switch between them with URLs structured like this: https://example.com ...

The debounce function seems to be malfunctioning as I attempt to refine search results by typing in the input field

Currently, I am attempting to implement a filter for my search results using debounce lodash. Although the filtering functionality is working, the debounce feature seems to be malfunctioning. Whenever I input text into the search bar, an API call is trigge ...

Lose the scrollbar but still let me scroll using the mouse wheel or my finger on the fullscreen menu

I am currently working on a fullscreen menu design. However, when the menu appears, some elements are not visible unless I apply the overflow-y: scroll property to the menu. But I don't like the appearance of the additional scrollbar that comes with i ...

Creating elegant text in HTML using only CSSLearn how to design stylish text using CSS without any additional code

Can you generate stylish text using just CSS in HTML? Check out this link for a great demonstration of fancy text. ...

Issue with Redirecting in React: REST requests are not successful

There's a text input that triggers a submission when the [Enter Key] is pressed. const [ query, setQuery ] = React.useState('') ... <TextField label="Search Codebase" id="queryField" onChange={ event => setQuery( ...

Vertical scroll through a list of columns with a stationary header, while allowing both the list and the header to

Check out this JSFiddle example: https://jsfiddle.net/jefftg/1chmyppm/ The layout currently has orange header columns and white list rows that scroll together horizontally. However, the goal is to have the white list rows scroll vertically while keeping t ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here? import { HttpCli ...

Having trouble showing the material-ui icon on my navigation menu

How can I use Material-UI icons like <AddOutlinedIcon /> in my nav menu without displaying the actual code before the menu name? Do I need to escape the icon code somehow to make it appear correctly? The intended result is to have a + icon displaye ...

Using the Grails asset-pipeline with an external JavaScript library

In transitioning from Grails 2 to Grails 3, I am facing the challenge of managing my JavaScript files with the asset-pipeline plugin. The issue lies in using external libraries such as globalize and ajax-solr, which are large and consist of multiple interd ...

Placing error notifications beneath my table rows for a more polished appearance

In the process of creating a review page for my app that showcases uploaded files, I've encountered an issue. Whenever a user uploads files with errors, I want to display a warning message below each specific file. Currently, I'm able to show the ...

Pop-up with a unique MediaBox design

Last week, I inquired about window pop-ups and have been brainstorming alternatives. One idea I had is to use mediabox/lightbox style pop-ups. Would it be feasible to create a link that opens a mediabox window off to the side when clicked? Users could dra ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

Is there an image overlapping another image?

Currently, I am working on developing a website for a Food Cart project in my class. One of the key features I want to incorporate is the ability for users to click on an image of a plate and have a different image representing the food appear on top of it ...

What is the best way to single out a specific item from a list to display in a component upon clicking in Vue.js?

To view the data of a specific item in the child component "comandasInd", I just need to click on the icon. <template> <v-data-table :items="comandas"> <template v-slot:items="props"> <td>{{ props.item.nombre }}</td& ...