Slider fade animation not functioning as expected

Why won't the last slide display? How can I ensure that the first image is shown immediately after the side loads, without any delay? I've attempted various solutions but always encountered issues (such as displaying two images simultaneously) and now this.

<!DOCTYPE html>
<html lang="pl">
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="https://use.fontawesome.com/19445204e2.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
        
        <script type="text/javascript">

        // Initial slide
        var numer = 0;
 
        function changeslide()
        {
            var imagesnumber=document.getElementById("slider").getElementsByTagName("img");

            for(var i = 0; i < imagesnumber.length; i++)
            {
                imagesnumber[i].style.display = "none";
            }
                
            // Display current index                
            $("#slide"+numer).fadeIn(500).css('display','block');

            if(numer >= imagesnumber.length-1)
                numer = 0;
            else
                numer++;
            
            timer1 = setTimeout("changeslide()", 3000);
        }
        </script>
        
    </head>
    <body onload="changeslide()">
        <div id="slider">
            <img src="slides/img1.jpg" id="slide1">
            <img src="slides/img2.jpg" id="slide2">
            <img src="slides/img3.jpg" id="slide3">
            <img src="slides/img4.jpg" id="slide4">
            <img src="slides/img5.jpg" id="slide5">
        </div>
    </body>
</html>

Answer №1

let count = 0;

function newSlide(){
            let timeout=0;
            if(count!==0){
              timeout=3000;
            }
            let images=document.getElementById("slider").getElementsByTagName("img");



            for(let x = 0; x < images.length; x++)
                {
                    images[x].style.display = "none";
                }

            // Display current index

            $("#slide"+count).fadeIn(500).css('display','block');


            if(count >= images.length-1)
                count = 0;

            else
                count++;



            timer1 = setTimeout("newSlide()", timeout);


        }

View on CodePen

Answer №2

function updateslide() {
  if (typeof this.counter === "undefined") this.counter = 1;
  var totalImages = document.getElementById("slider").getElementsByTagName("img");

  $("#slider img").css("display", "none");
  $("#slide" + counter).fadeIn(500).css('display', 'block');

  if (this.counter >= totalImages.length)
    this.counter = 1;
  else
    this.counter++;

  timer1 = setTimeout(updateslide, 3000);
}

I made adjustments to the function by moving the counter inside for better variable handling.

The restarting of the counter was premature, so I implemented a jquery solution instead of a for loop.

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

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Explore the hidden route of the input components

HTML: <div id="quiz"> <div id="question"> <p id="quiz-txt">What is your favorite color?</p> <ul id="quiz-opt"> <div id="ans"> <input type="checkbox" id="Red" value="Red" class="options"> ...

When incorrect credentials are entered, consider displaying toast notifications in the login screen

<button type='submit' action='#' class='btn btn-primary block full-width m-b' id='showsimple1'>Login</button> $name = $_POST['name']; $password = $_POST['password']; if(!($usr = $db ...

Decide whether an angular rotation is within the camera's field of vision inside a spherical object

Seeking assistance with a three.js project. I have set up a camera inside a SphereGeometry at position (0,0,0) and am projecting an image on the sphere's wall. My goal is to create interactive JS elements outside of the threejs framework that respond ...

Encountering Next.JS Router Issue: Unable to Access Properties of Null (specifically 'useContext')

As a beginner in Next.js and React, I'm facing an issue with redirecting users from the "Projects" page to the Product Page Details. Here's the code snippet I am using: const openProjectDetails = () => { Router.push('/api/' + props ...

Troubleshooting Proxy.php issues in conjunction with AJAX Solr

Attempting to access a Solr 4.5.0 instance located on a private server, http://12.34.56.789:8983/ The application resides at this web server address, http://www.mywebapp.com To facilitate accessing the JSON object within the Solr instance, I decided to ...

When a user toggles one div, the other toggled div should automatically close

Below is a snippet of code where I have implemented a functionality using vue.js to toggle different divs based on button clicks. The current setup allows for toggling individual divs when their corresponding buttons are clicked. However, I am looking to ...

Tips for saving the latest counter value in CSS and showcasing it as content in HTML

Here is an example of how my CSS code is structured: .page-number:after { counter-increment: page; } If we were to display 6 pages, it would look something like this: .page-number:after { content: 'Page ' counter(page) ' of'; } ...

React typescript props not appearing as potential defined, even after implementing the '?' optional operator and '| undefined'

I've noticed that my linter has suddenly stopped flagging potentially undefined properties passed into my React components. For instance: interface BooleanTypeObject { prop1: true } interface MyComponentProps { disable ...

How can we stop self shadowed faces from being illuminated?

Currently, I am working on creating a city scene in Three.js and experimenting with lighting and shadows. Specifically, I am focusing on a single building that was modeled in 3DS Max, then exported to OBJ format, and converted using a Python converter thro ...

issue involving extension that interrupts downloads

Trying to develop a browser extension that can intercept downloads and automatically rename them. manifest.json: { "name": " Book Renamer", "description": "Automatically rename downloaded ebooks from gutenberg.or ...

Is it possible for Chrome to permit my extension to send HTTPS requests to a server with a self-signed certificate?

My question is about sending AJAX (HTTPS) requests to a server that I own from the background page of my Chrome extension. I have found that without adjusting browser settings, it is difficult to send such requests to an unsigned/self-signed server. I am c ...

Removing a function when changing screen size, specifically for responsive menus

$(document).ready(function () { // retrieve the width of the screen var screenWidth = 0; $(window).resize(function () { screenWidth = $(document).width(); // if the document's width is less than 768 pixels ...

Trigger event listener of AngularJS directive on click and send information to it

During my exploration of AngularJS directives, I encountered a task that required me to activate the directive's listener upon clicking a button and passing data from the controller to it. Sample Directive app.directive('graphVisualization&apos ...

How does Socket.io facilitate a basic web socket connection with a specific URL?

My current project involves a client making a WebSocket request to the following URL: ws://localhost:3000/feed/XBTMUR https://i.sstatic.net/R7H9T.png On my server side, I am utilizing NodeJs with express running. I have decided to implement Socket.io in ...

Server-side script for communicating with client-side JavaScript applications

Currently utilizing a JavaScript library that uses a JSON file to display content on the screen in an interactive manner. (::Using D3JS Library) While working with clients, it is easy to delete, edit, and create nodes which are then updated in the JSON fi ...

Learn how to utilize Jquery to create a dynamic slide effect that toggles the

I am looking to change a banner on click functionality. Currently, I have hidden the 2nd banner and banner 1 is displayed. When the arrow is clicked, I want banner 1 to hide and banner 2 to show. The challenge is that I attempted using HTML for this task. ...

The onBlur event attached to a div is triggered when transitioning from one input element to another within the same div

Here's a scenario: I have a div with two input fields nested inside, like this: <div> <input placeholder="Input1"/> <input placeholder="Input2"/> </div> I have a requirement to trigger a specific ...

Expand or collapse in a sequential manner

Is there a way to ensure that only one table row expands at a time, causing the others to collapse? Any suggestions on achieving this? Here's the HTML code snippet: <table class="table"> <tbody> <tr class="parent" id="2479"> ...