Switch up the image every 10 seconds

Looking for assistance with changing images every 10 seconds in JavaScript.

Here are the HTML and CSS codes, I just need help adding some JavaScript to make it work:

HTML

<body onload = "imageChanger()">
    <div>
        <ul>
            <li><img src = "images/img1.jpg"/></li>
            <li><img src = "images/img2.jpg"/></li>
            <li><img src = "images/img3.jpg"/></li>
            <li><img src = "images/img4.jpg"/></li>
        </ul>
    </div>
</body>

CSS

div {margin: 50px auto; height: 500px; width: 800px; overflow: hidden; border: 10px solid;}
img {width: 800px; height: 500px;}
ul {list-style-type: none; padding: 0; margin: 0;}

I need help adding code to change the image on page load:

JS

function imageChanger()
{
    //Your code goes here
}

Answer №1

Here is the solution I came up with for a similar situation:

<body id="background">
<script>
$(function () { 
    var imageArray = ['BG-1.jpg', 'BG-2.jpg', 'BG-3.jpg', 'BG-4.jpg', 'BG-5.jpg', 'BG-6.jpg', 'BG-7.jpg', 'BG-8.jpg', 'BG-9.jpg', 'BG-10.jpg', 'BG-11.jpg', 'BG-12.jpg', 'BG-13.jpg', 'BG-14.jpg', 'BG-15.jpg', 'BG-16.jpg', 'BG-17.jpg', 'BG-18.jpg', 'BG-19.jpg', 'BG-20.jpg', 'BG-21.jpg', 'BG-22.jpg'] 

// sets background on page load
$('#background').css({ 'background-image': 'url(/Content/img/BackGround/' + imageArray[Math.floor(Math.random() * imageArray.length)] + ')', 'background-size': 'cover' })

// changes background every 10 seconds to random image from array
setInterval(function () { 
    $('#background').css({ 'background-image': 'url(/Content/img/BackGround/' + imageArray[Math.floor(Math.random() * imageArray.length)] + ')', 'background-size': 'cover' }) 
    }, 10000); 
});
</script>
</body>

Answer №2

If you want to cycle through images, the setInterval() function will do the trick.

Sample Code

let currentIndex = 0;

setInterval(switchImage, 10000);
switchImage(); //Initial call to hide the images at start

function switchImage() {
    currentIndex = (currentIndex + 1) % $('li').length; //Ensure wrapping back to index 0

    $('li:eq(' + currentIndex + ')').show().siblings().hide();
}

Try it out in this Fiddle

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

Issue with PHP form not saving data and correctly parsing output

I am facing an issue with my PHP page where it is supposed to grab responses from a form, insert the data into a table, and then display the response on the same page. I am using ajax to send form values without refreshing the page, but unfortunately, no i ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

Executing a JavaScript function on an HTML page within an embedded object tag

I am facing a scenario where I have a page with another page embedded using an object tag. The challenge is to call a JavaScript function from the "parent" page, specifically reaching a function within the embedded code. In the past, my solution involved ...

Implementing model synchronization on server initialization with Next.js and sequelize

When it comes to using Express with React on the backend, I'm accustomed to working in a server.js file to synchronize the database. However, I've recently started working with Next.js and noticed that there's no server.js file to sync the m ...

Tips for accessing basic information from these websites without encountering CORS issues

Having issues retrieving data from the following two sites: and Eurolottery. The CORS issue is causing the problem, and I was able to retrieve data using a Chrome CORS extension and the provided code below: var HttpClient = function() { this.get = fu ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

Comparing throwing exceptions in Node.js and Gevent

During a recent tech gathering, I heard an interesting claim about the behavior of callbacks and exceptions in Node.js and Gevent. The person mentioned that if a callback throws an exception in Node.js, it can crash the entire process, whereas in Gevent, a ...

How can default props be set for a nested object in Vue?

Here's how I've defined my props: myHouse = { kitchen:{ sink: '' } } I attempted to set the default props like this, but it didn't work as expected. props: { house: { type: Object, default: () => { ...

Having trouble getting gulp set up and running with npm?

I am currently in the process of setting up gulp using npm in order to execute my project. Based on my understanding, all I need to do is enter "npm install gulp" in the command line at the location of my project like this : https://i.stack.imgur.com/hPU ...

The feature of sorting appears to be malfunctioning within jQuery DataTables

I am having trouble implementing sorting in my data. Can you please help me understand why it is not working? What changes do I need to make so that the data can be displayed in order? <%@ page language="java" contentType="text/html; charset=ISO ...

Utilize jQuery to apply a border and background color to a table row when hovering over it

Is there a way to change the border of a table row along with its background color when the mouse hovers over it? Currently, I can only modify the background color using the following code: $(document).ready(function() { $(function() { $(&apos ...

Issue with triggering onclick event in both parent and child components

I am working with 2 components in Vue.js: An Accordion header that opens its content when clicked on. A Cog icon that opens a mini-modal menu. The issue arises when I click on the cog icon - I do not want the Accordion to open its content. Before click ...

Arranging fixed-width <div>s in rows of four for a sequential display

Below is the code that I am working with: <div style="margin: 0 auto; display:block; width: 916px; overflow: auto;"> <?php echo ""; echo "<i>Owned: $line->phone </i><br><br>"; $query ...

This error occurs when trying to assign a value to a property of a variable that is currently undefined

Having some issues with assigning the latitude and longitude values to a variable in my code. I am able to retrieve them correctly, but when trying to use them in another method (onUpload()), I am facing some errors. export class latlonComponent implement ...

Clicking on the div will automatically refresh the page

Within a div on my website, I have placed my site logo and other elements. I am looking to set it up so that when a user clicks on the site logo (the div), they will be redirected to the homepage. What is the best way to achieve this? Should I use onclic ...

Problem with UL LI styling in Internet Explorer 8

One issue I'm encountering is that a specific LI item in the list seems to be displaced from the others: https://i.sstatic.net/cxazD.jpg Have any of you experienced this problem as well? Any successful solutions or workarounds? ...

Utilizing a dropdown selection value to filter a list in JavaScript

I have an array of objects where I need to filter based on a dropdown selection. const itemsList=[{ "id":"123", "problems":{ "causes":[ { "SSEnabled": true, "IndusEnabled": false, "LogEnabled": true } ] } ...

Encountering an Issue with NextJS on GAE: EROFS Error indicating a read-only file system

Trying to deploy a customized Next.js application into Google App Engine has hit a snag. The project runs smoothly locally and on Google Cloud Platform CLI, but upon successful deployment using gcloud app deploy, an error arises when opening the app. 2020 ...

In Next.js, encountering an error when using canvas drawImage

I am attempting to upload a local image onto a canvas element, but I keep encountering an error: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement ...

Save an automatically generated number into a variable and use it to reference an image file for display. This process can be accomplished using JavaScript

I'm having trouble getting my images to display randomly on a page. The images are named 0 - 9.png and I am using a pre-made function for random number generation. However, when I try to call on this function later down the page, nothing appears. It ...