Creating a basic image carousel with JavaScript, CSS, and HTML

After running the code, I encountered an issue where the first image displays but then after one second, only a white blank screen appears with no further action. It seems like there may be an error in the JavaScript code. Below is the code that was attempted:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
img {
    width: 582px;
    height: 306px;

}

</style>
</head>

<body>

<img src="image-slider-1.jpg" id="myphoto" />

<script type="text/javascript">

var image=document.getElementById("myphoto");
var imageArray=("image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg");

var imageIndex=0;

function slide(){

image.setAttribute("src",imageArray [imageIndex] );
imageIndex++;
if(imageIndex>=imageArray.length) {
    imageIndex=0;

}
}
setInterval(slide,1000);

</script>
</body>
</html>

Any assistance or guidance would be greatly appreciated.

Answer №1

You should definitely give this a try, it did the trick for me!

const interval = 3700;  // Set the time interval

const picsArr = [
    'abc.jpg',
    'def.jpg',
    'ghi.jpg'
];

let timer; // Timer variable
let currentIndex = 0;
const picLength = picsArr.length;

const preloader = [];

for (let i = 0; i < picLength; i++) {
       preloader[i] = new Image();
       preloader[i].src = picsArr[i];
}

function runBackgroundSlideShow() {
    if (document.body) {
        document.body.background = picsArr[currentIndex];
        currentIndex++;
        
        if (currentIndex > (picLength - 1)) {
            currentIndex = 0; // Start from the first picture again
        }

        timer = setTimeout('runBackgroundSlideShow()', interval); 
    }
}

Answer №2

Your expectation is not met by the following line of code:

var imgArr=("img1.jpg","img2.jpg","img3.jpg","img4.jpg","img5.jpg");

If you check the content of imgArr after this line, it will only contain the string "img5.jpg". (Why? Learn about how the comma operator works in javascript.)

To correctly define an array of strings, use the [] notation:

var imgArray=["img1.jpg","img2.jpg","img3.jpg","img4.jpg","img5.jpg"];

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

Guide on updating directory images by uploading a new one directly onto the site

As someone who is new to HTML, I have a question about updating images on my website through an "admin" page. Currently, I have two websites set up - the main site displays an image from the "images" folder, and the second site serves as an admin page. M ...

Tips for updating content (wishlist) without the need to refresh the page

Currently experimenting with the TMDb API to enhance my PHP skills. I've successfully created a wishlist feature and now looking to optimize the script. A function is implemented on each movie page for adding movies to the wishlist. function getButt ...

Is it possible to submit a select menu without using a submit button within a loop?

I'm having an issue with my code that submits a form when an option in a select box is clicked. The problem arises when I try to put it inside a loop, as it stops working. Can anyone assist me with this? Below is the code snippet causing trouble: &l ...

Just starting out with CSS and coding. Setting up radio buttons and divs for a simple beginner's gallery

One challenge that perplexes me is how to reposition the concealed divs below the radio buttons with labels. Check out my HTML here View my CSS code here /*color palette: abls [lightest to darkest] #eeeeee #eaffc4 #b6c399 ...

I'm noticing that my Tailwind styles don't take effect until I redefine them. What could be causing

My Tailwind classes are giving me trouble. I faced an issue when I created a new component in the directory and placed my Button component there. Whenever I restart the project in terminal, the styles do not apply to my button unless I manually define th ...

Can I switch between different accounts on Auth0?

While utilizing next-auth for user sign-ins, I've noticed that there isn't a clearly visible option to switch accounts after signing in. Additionally, if users enter incorrect credentials, there doesn't seem to be a way to sign in with a dif ...

What is the best way to align an element next to another using id or class?

I am looking to align the search element next to either "Media Heading 1" or "Media Heading 2" based on their id/class. For instance: Assume I have an element with the class of "media-item-1" and I aim to position the search div alongside that element us ...

Watching a service's attribute from within a route in the EmberJS framework

There seems to be a concept that I'm struggling to grasp here. To my understanding, any instance of Ember.object should be able to observe properties on another instance of Ember.object. In my scenario, there is a service, a router, and a component i ...

How can we efficiently validate specific fields within arrays and objects in express-validator by utilizing the body() method?

I have organized my field names in an array as follows: const baseFields = [ 'employeeNumber', 'firstName', 'lastName', 'trEmail', 'position' ]; These are the only input fields I need to focus on for valid ...

PHP POST request with an additional value being sent

Greetings as this is my debut post! Currently, I am facing a challenge in my project. As seen in the screenshot provided, I have several names fetched from the database and displayed in the main menu. Upon clicking the "modal" button, a Bootstrap modal wi ...

ParcelJs is having trouble resolving the service_worker path when building the web extension manifest v3

Currently, I am in the process of developing a cross-browser extension. One obstacle I have encountered is that Firefox does not yet support service workers, which are essential for Chrome. As a result, I conducted some tests in Chrome only to discover tha ...

Troubleshooting Karate - jbang.execute() (Node npm)

Need help with a question that's part of our project presentation. We are working on controlling the output of KARATE, ensuring it returns an OK or a KO depending on the test result. Currently, it always gives back 0 regardless of success or failure. ...

Problem displaying images in Mean stack app using CSS background-image and Webpack

Currently, I am enhancing my skills by working on my own projects. One of the projects I'm focused on right now is designing a MEAN-stack app that utilizes Webpack. In the past, I encountered an issue where I couldn't display images in my app. Ho ...

inside the connect module, the res._renderHeaders function is located

Currently, I am delving into the patch.js file within the connect module. In it, I found some intriguing code snippets: var http = require('http') , res = http.ServerResponse.prototype , setHeader = res.setHeader , _renderHeaders = res._re ...

React Native ScrollView ref issue resolved successfully

I'm trying to automatically scroll to the bottom of a flatlist, so here's what I have: const scrollViewRef = useRef(); //my scroll view <ScrollView ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scr ...

Choose the data attributes you want to include and attach them to input elements using plain JavaScript

Creating a User Information form with a select element containing four options, each with data attributes. Under the select are input types to populate the data attributes when selected. Looking for help in achieving this using plain JS and onchange event. ...

Personalize the color scheme for your timeline paper

I am interested in customizing this specific example of a personalized timeline: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Timeline from '@material-ui/lab/Timeline'; import Timeli ...

Chosen Dropdown selection - Retrieve/Receive information

One of the challenges I'm facing involves a dropdown list on my web form that contains various dates. My main query is: How can I retrieve data for the selected date from a MySQL database and present it to the user? Additionally, if the chosen date do ...

Adjust the spacing of a div based on the fluctuating height of another dynamically changing div

Is it possible to dynamically adjust the margin of a div using jQuery or JS? Currently, I have set a margin on a div by calculating the height of a container that includes images. var articleImageHeight = $('.slides_control').height(); $(' ...

Implementing JSON responses in Express JS

My apologies for any language errors as English is not my first language, I am using Google Translate :) I have a question.. Here is the MySQL Query I am working with: SELECT destinations.*, questions.*, answers.* FROM destinations INNER JOIN questions ...