Adjust the background of the page at regular intervals

I currently have:

<script type='text/javascript'>
var imageID=0;
function changeimage(every_seconds){
//change the image
if(!imageID){
    document.getByTagName("body").src="icwXI.jpg";
    imageID++;
}
else{if(imageID==1){
    document.getByTagName"body").src="JvuP9.jpg";
    imageID++;
//call same function again for x of seconds
setTimeout("changeimage("+every_seconds+")",((every_seconds)*20)); 
</script>
</head>
<body style='background: url(icwXI.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;' onload='changeimage(1)'>

The goal is to display icwXI.jpg as the initial body background image, then switch to JvuP9.jpg after 20 seconds, and cycle back to icwXI.jpg 2 seconds later.

Despite my limited JavaScript skills, the code does not seem to be functioning correctly.

Thank you.

Answer №1

Generate a collection of background images - below you will find an example using placekitten images. Next, establish a function that switches the background with the next image in the collection. To keep track of our current position, a variable will be used (you could consider using the .indexOf method on arrays in modern browsers, however, support may be limited in certain environments).

Lastly, we will set up an interval that triggers every 23 seconds. This interval will execute the swapBG function and then immediately set a timeout to repeat the function after 2 seconds.

// backImg keeps track of the current image displayed
// dbStyle is a shortcut to access the body's style properties
// backgnd contains a list of background images
var backImg = -1,
    dbStyle = document.body.style,
    backgnd = [
        'url(http://placekitten.com/350/350)',
        'url(http://placekitten.com/349/349)'
    ]; 

// Progresses through background images, looping back to the start
// when reaching the end of the list
function swapBG() {
    dbStyle.backgroundImage = backgnd[ backImg++ ]
        ? backgnd[ backImg ]
        : backgnd[ backImg = 0 ];
}

// Call swapBG() right away
swapBG();

// Set up an interval that triggers every 23 seconds
setInterval(function(){
   swapBG();
   // Set a timeout to run after 2 seconds
   setTimeout(function(){ 
       swapBG()
   }, 2000 );
}, 23000);​

Live Example: http://jsfiddle.net/XsAWB/2/

Answer №2

  1. Before you proceed, make sure to address the syntax errors present in your code. Remember to close all opening { brackets and fix the missing parenthesis in the document.getByTagName function.

  2. It's important to note that your function does not have a delay before changing the background image on its first call. Consider implementing a sleep or timeout to achieve the desired effect.

  3. When using setTimeout() to repeat the function, remember that the second parameter represents milliseconds, not seconds as you may have initially thought.

  4. Update your function to handle multiple background changes by adjusting the conditions based on the imageID variable. Make sure to account for each background image you want to cycle through.

  5. Correct the method for changing the background image from

    document.getTagByName("body").src
    to
    document.body.style.backgroundImage
    for accurate results.

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

To ensure proper functionality, make sure that Python Selenium's Geckodriver is correctly

I want to automate form filling using Selenium. Below is the HTML code for the form: <!DOCTYPE html> <html> <body> <h2>Text input fields</h2> <form> <label for="fname">First name:</label><br& ...

Use jQuery to switch the class of the designated DIV in the showcasing slider

Check out this jQuery slider example where I have two Divs - DIV ONE and DIV TWO. Can you help me figure out how to: 1) Automatically change the class of DIV ONE from "test" to "testc" when Slide 1 is displayed by the slider. 2) Automatically update DIV ...

An empty array is being returned from a mongoose function call

I'm currently working on a project that involves fetching random values from MongoDB using mongoose and storing them in an array. However, I am facing an issue where the array appears to be empty outside the function: exports.Run = (req, res) => { ...

What is the best way to retrieve the DOM of a webpage that uses MP4 file extension?

I'm attempting to access the DOM within a page that has an MP4 extension. The page isn't a video or audio file, it's just HTML with an MP4 extension "". I've included the code I'm using to try and access it using Simple HTML DOM. T ...

Angular's implementation of deferred only displays the final value in the loop

I've created a personalized synchronization process that queues up all my sync records in sequence. When my service retrieves multiple sync records, it processes them and updates the last sync date for successful records, or logs errors for failed rec ...

Markdown Custom Parsing

Every week, I create a digest email for my university in a specific format. Currently, I have to manually construct these emails using a cumbersome HTML template. I am considering utilizing Markdown to automate this process by parsing a file that contains ...

How can I ensure the footer stays at the bottom of the page using a table layout?

For quite some time now, I've been working on achieving a table layout with a sticky footer. My specific requirement is for the footer to remain fixed at the bottom even when zooming in or out. However, whenever I try to adjust the zoom level of the w ...

Limiting the input frequency when executing a query with the `urql` GraphQL Client in React.js

My slider functions similarly to this one from Zillow's GitHub. It has minimum and maximum values, and triggers a query whenever the sliders are adjusted. The issue I'm facing is that the query is extensive, causing delays. I am looking for a wa ...

Tips for adjusting the speed of animations in Odometer/vue-odometer

Referencing the Odometer documentation at duration: 3000, // Adjusts the expected duration of the CSS animation in the JavaScript code Even though my code is set up like this, the duration parameter doesn't seem to be effective: <IOdometer a ...

Issue with scrollIntoView in devices with a width lower than 1200px

In my Angular 5 project, I have a table where each row is generated dynamically using *ngFor and given an id based on the username. <tbody *ngFor="let User of FullTable; let i = index"> <tr id='{{User.username}}'> <th scope="r ...

The class type "selectLabel" passed to the classes property in index.js:1 for Material-UI is not recognized in the ForwardRef(TablePagination) component

Just started using react and encountering a repetitive error in the console after adding this new component. Here is the full error message: Material-UI: The key selectLabel provided to the classes prop is not implemented in ForwardRef(TablePagination). ...

"Learn the process of converting HTML content into a string in an Android application and then displaying

I utilized this/this to Print Receipts in part of POS(Point of Sale) from EPSON Printer Obtaining data Json from URL (within the Json Object is html print template): { "response": { "status": "<table>.... </table>" } } Hence, ...

Discovering the file extension and ensuring its validity when imported from Google Drive

I am facing an issue with a select tag that has 3 options: powerpoint, pdf, and spreadsheet. When uploading from Google Drive, there is no validation in place, so I can give a ppt link to the pdf option and it will still upload. Can someone help me with va ...

The JSON GET method displays HTML content when accessed through code or console, but presents a JSON object when accessed through a web address

I am currently trying to execute the following code: $(document).ready(function () { $.ajax({ url: 'http://foodfetch.us/OrderApi/locations', type: 'GET', success: function(data){ alert(data); ...

Utilizing Jquery cycle to overlay a div on top of a scrolling image

Hey there! I'm currently using the jquery.cycle.all.js plugin for my website. I've encountered an issue where I want to position a menu div on top of an image slider. The menu is in the correct location, but unfortunately, it's hidden benea ...

Concealing URL in client-side fetch request within Next.js

A contact form built in Next.js makes use of the FormSubmit API to send emails upon clicking the submit button. Below is the code for the onSubmit handler: const handleSubmit = async (e) => { e.preventDefault(); const res = await fetch("https:/ ...

A textarea with a height of zero is still visible

My goal is to create collapsible widgets within a side panel on my webpage. Overall, the functionality works smoothly. I am able to adjust the height of child divs to 0px with a transition, causing them to disappear. However, I have run into an issue wher ...

Is it possible to programmatically hide the Textarea and submit button for each row in a PHP-generated database table?

After spending a considerable amount of time on this project, I'm looking to incorporate a JavaScript effect (hide/unhide) into a basic submit form. Although the functionality is successful, it seems to be limited to only one row in the database tabl ...

jQuery fails to recognize response

Can anyone figure out why my alert isn't functioning correctly? <script type="text/javascript"> function SubmitForm(method) { var login = document.form.login.value; var password = document.form.password.value; ...

The fitBounds and panToBounds functions in react-google-maps fail to properly adjust the map's size

const Map = withGoogleMap(props => { const { activeMarker, zoom, center, showInfoWindow, products } = props; const [selectedPlace, setSelectedPlace] = useState(null); // Code to iterate through items and adjust map size, center, and zoom to inclu ...