Creating a Visual Presentation with Background Image Transition in HTML, CSS, and JavaScript

Seeking assistance in setting up a basic background image slideshow on my website. I have been unable to locate a suitable tutorial online, so I'm reaching out here for guidance.

HTML:

<body>
   <h3>Welcome!</h1>
   <p>Lorem ipsum dolor sit amet</p>
</body>

JS:

var i = 0;
var images = [];
var slideTime = 3000; // 3 seconds

images[0] = '/img/bg1.jpg';
images[1] = '/img/bg2.jpg';
images[2] = '/img/bg3.jpg';

function changePicture() {
    document.body.style.backgroundImage = images[i];

    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }

    setTimeout("changePicture()", slideTime);
}

window.onload = changePicture;

CSS:

body {
    background-image: url("img/bg2.jpg");
    background-position: center;
    background-size: cover;
}

Answer №1

To properly add a background image in HTML, the URL of the image file must be specified within the url() function.

var i = 0;
var images = [];
var slideTime = 3000; // 3 seconds

images[0] = 'https://example.com/image1.jpg';
images[1] = 'https://example.com/image2.jpg';
images[2] = 'https://example.com/image3.jpg';

function changePicture() {
    document.body.style.backgroundImage = "url(" + images[i] + ")";

    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }
    setTimeout(changePicture, slideTime);
}

window.onload = changePicture;
body {
    background-image: url("https://example.com/image1.jpg");
    background-position: center;
    background-size: cover;
}
<h3>Welcome!</h3>
   <p>Lorem ipsum dolor sit amet</p>

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

Is there a way for me to view the output of my TypeScript code in an HTML document?

This is my HTML *all the code has been modified <div class="testCenter"> <h1>{{changed()}}</h1> </div> This is my .ts code I am unsure about the functionality of the changed() function import { Component, OnInit } f ...

IE8 triggers automatic download upon receiving JSON response using jQuery

Can you help me make IE8 compatible with this code using jQuery to handle an ajax request that returns data as JSON? $.ajax({ url: formAction, type: 'post', dataType: 'json', data: form, success: ...

The float right attribute doesn't stay contained within the box; instead, it drifts outside the box

I've been struggling to keep this box fixed at the top of the browser, but I'm facing an issue with the positioning on the right side. I can't seem to figure out how to solve it, so I'm reaching out for some help. #StickyBar #RightSide ...

What causes a syntax error when trying to create an array of objects within a map using colons?

In my Google Apps Script, I created a function to retrieve the date and subject of emails with a specific label in Gmail. However, when attempting to store each result as an object, I encountered a SyntaxError: unexpected token ':' issue. Althoug ...

Tips on how to showcase the current time in the local timezone on Next.js without encountering the error message "Text content does not match server-rendered HTML."

Currently, I am sharpening my Next.js skills by building a blog. My current challenge involves formatting a static ISO time string (which represents the creation time of blog posts) to match the local timezone of the user. <div className='post-time ...

Issues with the functionality of minimized AngularJS JavaScript files

I combined all JS files into one and minified them, but now none of the site features are working. There were too many separate JS files to include individually, so I decided to merge them together. Is there a better method to reduce the number of HTTP r ...

Error: The getter callback for the component `RNCSafeAreaProvider` must be a function, but it is currently undefined

After attempting to update my React Native app's dependencies using npm update, chaos ensued. To rectify the situation, I reverted back to the previous package-lock.json, deleted the node_modules folder, and re-ran npm i. Surprisingly, instead of res ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

Turning a stateful React component into a stateless functional component: Ways to achieve functionality similar to "componentDidMount"

I recently developed a small, stateful React component that utilizes Kendo UI to display its content in a popup window when it loads. Here is a snippet of the code: export class ErrorDialog extends React.Component { constructor(props, context) { sup ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Unable to Locate Gulp Packages

Whenever I try to run the command gulp in my terminal, my gulp modules are not being found. Surprisingly, all other commands like node -v, gulp -v, and npm -v are working perfectly fine with the latest versions installed. I have tried running these command ...

Tips for solving the problem of TSX error where 'ReactNode' cannot be assigned with 'void' type

I've been attempting to loop through the Mui component MenuItem using a forEach loop, but I'm encountering an error stating 'Type 'void' is not assignable to type 'ReactNode''. Here's the section of my code caus ...

Issues with d3.js transition removal functionality not functioning as expected

Having an issue with a d3.js visualization that involves multiple small visualizations and a timeline. When the timeline changes, data points are supposed to be added or removed accordingly. Here is the code snippet responsible for updating: var channels ...

Changing the class of a div in JavaScript from one class to another

On my HTML page, I have a div with a CSS class assigned to it. The goal is to switch the current class for another when a button is clicked. It's crucial that not a single CSS property within the class is altered - the entire class must be replaced en ...

Can JavaScript be used to mimic selecting a location from the autocomplete dropdown in Google Maps API 3?

Currently, I am attempting to automate the process of selecting items from the autocomplete dropdown in the Google Maps API v3 places library using jQuery. However, I am facing difficulty in identifying the necessary javascript code to select an item from ...

Error: Attempting to access a property of an undefined object resulting in TypeError (reading 'passport')

I am currently working on a project that requires me to display user profiles from a database using expressjs and mongoDB. However, I have encountered an issue and would appreciate any solutions offered here. Here is the code from my server: const express ...

Run javascript code after the page has transitioned

Struggling to create a dynamic phonegap app with jQuery Mobile, the issue arises when loading JavaScript on transition to a new page. The structure of my index page is as follows: <body> <div data-role="page" id="homePage"> <div data- ...

Click on the window.location.href to redirect with multiple input values

I am facing a challenge with my checkboxes (from the blog label) and the code I have been using to load selected labels. However, this code seems to only work for one label. Despite multiple attempts, I have found that it only functions properly with one ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

Guide on configuring and executing AngularJS Protractor tests using Jenkins

I am encountering an error with the following configuration: ERROR registration capabilities Capabilities [{platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=}] does not match the current platform LINUX 18:17:05.892 INFO ...