Creating a Basic Slideshow using Javascript

I've been attempting to create a slideshow using only JavaScript, but I've run into an issue. When I set the divs to change on click, it works perfectly fine. However, when I try to set it to change at specific intervals, it doesn't work.

var numSlide = 0, currentSlide=0;
var slides = new Array;

function slideShow(){
img = document.getElementsByClassName("slideDesign");
for (i=0; i < img.length; i++){

slides[numSlide]=img[i];

if (numSlide == 0){
img[i].style.zIndex ="4";
}
else{
img[i].style.display = "0";
}
img[i].onclick = slideCheck;
numSlide++;

}
}

function slideCheck(){
slides[currentSlide].style.zIndex="0";
currentSlide++;
if(currentSlide >= numSlide){
currentSlide = 0;
}
slides[currentSlide].style.zIndex= "4";
}


window.onload = slideShow;
.slideDesign{
width: 100%;
height:400px;
max-height:800px;
position: absolute;
top:0;
transition: z-index 1s;
}
#div1{
background-color:black;
}
#div2{
background-color:red;
}
#div3{
background-color:blue;
}
#div4{
background-color:green;
}
#div5{
background-color:cyan;
}
<!DOCTYPE HTML5>
<html>

<head>
<link rel="stylesheet" href="style.css">    
<script type="text/javascript" src="script.js"></script>
</head>

<body>
<div id="slideShow">

<div id="div1" class="slideDesign"></div>
<div id="div2" class="slideDesign"></div>
<div id="div3" class="slideDesign"></div>
<div id="div4" class="slideDesign"></div>
<div id="div5" class="slideDesign"></div>


</div>    

</body>


</html>

In the JavaScript code, just before the end of the slideShow function, I can call the slideCheck function by clicking on the div and the div changes accordingly. But if I change that line to window.setInterval("slideCheck();", 3000), it just doesn't work and I can't figure out why.

Answer №1

In case you're not interested in creating your own custom Sliding feature, you might want to check out . Hopefully, this information is useful to you.

Answer №2

To start, make sure to invoke your init function (slideShow) followed by your slide change function (slideCheck) with a specified interval.

var numSlide = 0, currentSlide=0;
var slides = new Array;

function slideShow(){
    img = document.getElementsByClassName("slideDesign");
    for (i=0; i<img.length; i++){

        slides[numSlide]=img[i];

        if (numSlide == 0){
            img[i].style.zIndex ="4";
        }
        else{
            img[i].style.display = "0";
        }
        img[i].onclick = slideCheck;
        numSlide++;

    }
}

function slideCheck(){
    slides[currentSlide].style.zIndex="0";
    currentSlide++;
    if(currentSlide >= numSlide){
       currentSlide = 0;
    }
    slides[currentSlide].style.zIndex= "4";
}
// Start the slide show
slideShow();
// Slide every 3 seconds
window.setInterval(slideCheck, 3000);
.slideDesign{
    width: 100%;
    height:400px;
    max-height:800px;
    position: absolute;
    top:0;
    transition: z-index 1s;
}
 #div1{
    background-color:black;
    }
 #div2{
    background-color:red;
    }
  #div3{
    background-color:blue;
    }
 #div4{
    background-color:green;
    }
 #div5{
    background-color:cyan;
    }
<!DOCTYPE HTML5>
<html>

<head>
<link rel="stylesheet" href="style.css">    
<script type="text/javascript" src="script.js"></script>
</head>

<body>
<div id="slideShow">

<div id="div1" class="slideDesign"></div>
        <div id="div2" class="slideDesign"></div>
        <div id="div3" class="slideDesign"></div>
        <div id="div4" class="slideDesign"></div>
        <div id="div5" class="slideDesign"></div>


</div>    

</body>


</html>

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

Utilize a randomized dynamic base URL without a set pattern to display a variety of pages

I am intrigued by the idea of creating a dynamic route that can respond to user-generated requests with specific files, similar to how Github handles URLs such as www.github.com/username or www.github.com/project. These URLs do not follow a set pattern, ma ...

Toggle visibility of div based on current business hours, incorporating UTC time

UPDATE I have included a working JSFiddle link, although it appears to not be functioning correctly. https://jsfiddle.net/bill9000/yadk6sja/2/ original question: The code I currently have is designed to show/hide a div based on business hours. Is there a ...

Binding arguments to child functions within Vue components

When working with React, it's a common practice to bind parameters for child components in the following manner: <Child onChange={e => doThing(complex.variable.inParentScope[3], e.target.value)} foo="bar" /> In Vue, I want to ach ...

When attempting to load the table from JSON, the error message "Cannot read property 'name' of null" occurs in the fooplugins/Footable plugin

I am facing an issue while trying to integrate the "FooTable" plugin with ajax calls. Everything works perfectly fine when I directly input the JSON data or load it from a JSON file using $.get('....json'). However, when attempting to fetch the t ...

Step-by-step guide on incorporating a new JSON object into an array to display its elements as components on a webpage

Could I adjust the state of an array by incorporating values from a data.js file as a starting point? The process involves executing the setAllThingsArray function to add a new element, determined by the setThingsArray function based on the previous state ...

There was an issue serializing the `.product` data that was returned from `getStaticProps` in the "/prints/[name]" route in Next.js

My Strapi nextjs application has 2 categories of products. Everything works fine locally, but I encounter an error when trying to build: Error serializing .product returned from getStaticProps in "/prints/[name]". Reason: undefined cannot be se ...

A time-tracking counter that tallies the amount of time users spend on the webpage

I'm currently working on a code that tracks the time spent on a page starting from when it was clicked. My challenge now is figuring out how to capture the time when the submit button is clicked and store it in the database. < script > var ...

Disabling ngIf but still utilizing ngContent will render the template bindings

Creating a basic component in the following way: @Component({ selector: 'loader', template: `<div *ngIf='false'> <ng-content></ng-content> </div>`, }) export class Loader {} When it is imple ...

Steps to insert an image object into a table

Note: The image in the database is named "profileImage." I want to create a dynamic image object similar to other objects when I insert this code. { label: "Image", name: "profileImage", } It will display the image endpoint as 3704545668418.PNG and ...

Rampant number of objects contained within box element

I am currently working on a box component that contains flex items. Unfortunately, I am facing an issue where the box width remains constant and causes overflow when I try to reduce its size in order to accommodate all the items. Can anyone provide guidanc ...

Discovering additional element information while utilizing the 'Sortable' feature

My Current Objective: In my setup, I have a 'calendar' comprising 5 columns, each column containing 5 separate divs known as timeslots. The main purpose here is to show appointments in these specific timeslots and utilize JQuery's Sortable ...

Issue with jQuery not being able to retrieve the data from my CSS property

this is my custom style code: table.table tr td{ padding:30px; border-left: double 1px white; border-bottom: double 1px white; cursor:cell; } and below is the jQuery script I am using: $(document).ready(function () { ...

Obtain the unique identifier of the chosen option using material-ui's autocomplete feature

I am currently implementing the autocomplete feature using material-ui. The data in the "customerList" displayed in the search field works fine. However, I am facing an issue with retrieving the "ID" number of the selected data. My goal is to obtain the ID ...

creating keys dynamically in a Mongoose schema using Node.js JavaScript

I consider myself an intermediate in node.js. Within my mongoose schema, I have a variety of fields listed below: result_1 result_2 result_3 result_4 result_5 The data will come in numeric form (1-5) as the result number, and based on this number, I nee ...

Steps for adding SVGs to a <div> element

While there are numerous solutions on Stack Overflow detailing how to append an SVG in a div, none of them have proven successful for me. This could be due to my lack of experience with SVGs. Therefore, I am generating an SVG on my node server and the ...

How can I effectively update Bootstrap 4 in a Rails environment?

After attempting to update my Rails 5 project from Bootstrap 4 Alpha 6 to the final version 4.0.0, I confirmed that the v4.0.0 gem was installed (with the alpha version gem uninstalled). However, upon running my project in development mode, I discovered th ...

Obtain HTML tags from RSS CDATA section

Is there a way to extract HTML tags from a CDATA tag in an RSS feed? I have utilized a basic jQuery function to retrieve the JSON object from the RSS, below is my code: $.get("someURL", function(data) { console.log('InGet'); ...

Ensure advertisements are easily accessible and not visible to screen-reading tools

I oversee the management of numerous ads on a website. My goal is to enhance their accessibility, and though I have been doing research, there seems to be limited information available on how to achieve this effectively. While I continue my investigation, ...

Tips for adjusting a web address provided by a user

I have a JavaScript code that prompts the user to input a URL and then appends it to a div. The code is working fine, but now I am trying to add functionality to edit the entered URL by changing the width and height of any iframes before appending them. ...

How to place a div with 100% width at the bottom of a float with a fixed width

Each day the same question seems to pop up, yet this particular issue has me stumped... My goal is a simple one - I aim to design a fixed width layout with 3 columns, while ensuring that the header and footer stretch across 100% of the screen. Everything ...