A neutral-toned backdrop that briefly shows up for a quick 7-second interlude during a background-image

Recently I created a website. On this website, there is a feature where 3 images change every 7 seconds for a total of 3 cycles.

The code snippet used for this functionality is as follows:

var swap;
function run(interval, frames) {
    var int = 1;

    function func() {
        document.body.id = "b"+int;
        int++;
        if(int === frames) { int = 1; }
    }

    var swap = window.setInterval(func, interval);
}

run(7000, 3);

Additionally, here is the second part of the code (which I believe to be error-free):

$(window).scroll(function(){
    //... your logic goes here...
    $("body").css("background-image", "url(1.jpg)");
    if(youWantToStopTheInterval){
        window.clearInterval(swap);
        $("body").css("background-image", "url(1.jpg)");
    }
});

CSS styling related to the background images:

#b1 {
    /* Location of the image */
    background-image: url(1.jpg);
    /* Background image is centered vertically and horizontally at all times */
    background-position: center center;
    /* Background image doesn't tile */
    background-repeat: no-repeat;
    /* Background image is fixed in the viewport so that it doesn't move when 
     the content's height is greater than the image's height */
    background-attachment: fixed;
    /* This is what makes the background image rescale based
     on the container's size */
    background-size: cover;
    /* Set a background color that will be displayed
     while the background image is loading */
    background-color: #464646;
}
#b2 {
    /* Location of the image */
    background-image: url(2.jpg);
    /* Background image is centered vertically and horizontally at all times */
    background-position: center center;
    /* Background image doesn't tile */
    background-repeat: no-repeat;
    /* Background image is fixed in the viewport so that it doesn't move when 
     the content's height is greater than the image's height */
    background-attachment: fixed;
    /* This is what makes the background image rescale based
     on the container's size */
    background-size: cover;
    /* Set a background color that will be displayed
     while the background image is loading */
    background-color: #464646;
}
#b3 {
    /* Location of the image */
    background-image: url(3.jpg);
    /* Background image is centered vertically and horizontally at all times */
    background-position: center center;
    /* Background image doesn't tile */
    background-repeat: no-repeat;
    /* Background image is fixed in the viewport so that it doesn't move when 
     the content's height is greater than the image's height */
    background-attachment: fixed;
    /* This is what makes the background image rescale based
     on the container's size */
    background-size: cover;
    /* Set a background color that will be displayed
     while the background image is loading */
    background-color: #464646;
}

Upon refresh or page load, you may notice a brief moment of grey background before the images cycle properly. Any ideas why this happens or how it can be resolved?

Answer №1

Before setting the interval to start changing images, make sure to run the function to set the initial image. This is why there is a blank moment for 7 seconds at the beginning.

One reason you may not see all the images is because you reset the int variable before it can reach its maximum value. Consider adjusting your if statement accordingly.

Check out this code on JSFiddle: http://jsfiddle.net/AtheistP3ace/5f566hrc/

var swap;
function run(interval, frames) {
    var int = 1;

    function func() {
        document.body.id = "b" + int;
        int++;
        if(int > frames) { int = 1; }
    }

    func();
    var swap = window.setInterval(func, interval);
}

run(7000, 3);

While this approach works, changing IDs of elements dynamically may not be the best practice. There are likely more efficient ways to handle this, such as using classes instead of constantly modifying element IDs.

Updated Fiddle with class implementation: http://jsfiddle.net/AtheistP3ace/5f566hrc/1/

var swap;
function run(interval, frames) {
    var int = 1;
    var previousClass = "";

    function func() {
        if (previousClass != "") {
            document.body.classList.remove(previousClass);
        }

        previousClass = "b" + int;
        document.body.classList.add(previousClass);
        int++;

        if(int > frames) { int = 1; }
    }

    func();
    var swap = window.setInterval(func, interval);
}

run(7000, 3);

CSS styling:

.b1 {
    ...
}
.b2 {
    ...
}
.b3 {
    ...
}

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

When using Websocket, an error message stating "Invalid frame header" will be triggered if a close message of 130 or more characters is sent

I am utilizing the ws node.js module along with html5's WebSocket. The Websocket connection is established when a user triggers an import action, and it terminates once the import is completed successfully or encounters an error. At times, the error ...

What is the best way to implement a scroll-into-view feature for a newly added list item in Vue.js?

I am currently utilizing vueJS to create a task viewing application. My goal is to make the div containing the list focus on the newly added list item immediately after adding a new task. Here's the HTML code from my template for the task list: < ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

Eliminate duplicate entries in typeahead.js by ensuring unique data sources for both prefetch and remote

Currently, I have implemented typeahead.js with both prefetch and remote data sources. You can check out the example here. $(document).ready(function() { var castDirectors = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('val ...

Mastering the use of SVG icons in Angular 4+: A comprehensive guide

I have an icon.svg file with a collection of icons that I would like to use in my app, similar to how we display material icons. Does anyone have any ideas on how to include the file in the app and use these icons? I've tried looking for solutions a ...

Tips for creating a new tab or window for a text document

Below code demonstrates how to open a new tab and display an image with a .jpg extension. Similarly, I want to be able to open a text document (converted from base64 string) in a new tab if the extension is .txt. success: function(data) { var ...

"Trouble with Angular's http.get method failing to retrieve data from MySQL through Node

I am struggling to retrieve data from MySQL using Angular and Node.js. Despite trying, I am unable to make it work. When I check Postman using the link http://localhost:8080/locations, I can see the data. { "status": "200", "items": [ { "cit ...

Is there a way to invoke a different function within a class from a callback function in an HTTP request?

Having an issue with my HTTP GET request function in the "CheckPrice" class. When trying to call another function within the class callback, it's showing as undefined. Any suggestions? const got = require("got") class PriceCheck { constructor() { ...

Ways to resolve - Error: Unable to access 'comments' property of null

I am currently working on developing a blog web application and I am facing an issue with enabling user comments on posts. Despite extensive research and attempts to troubleshoot by searching online, I have not been able to find a solution. I have been str ...

I've encountered some issues with importing pagination from modules after installing SwiperJs

Having some issues with importing pagination from modules in SwiperJs for my nextjs project. The error message "Module not found: Package path ./modules is not exported from package" keeps popping up. I have tried updating the module to the latest version ...

Unable to establish a connection with the websocket server

I set up a websocket server on my host at <www.example.com>, but for some reason, the client is unable to connect to it. Here is the code : Server.js : const ws = new require('ws'); const wss = new ws.Server({noServer: true}); const htt ...

What is the best way to transfer a variable from an @Input property to a service within an Angular2 component?

I'm tackling what seems like a simple task, but I'm struggling to figure it out. My issue is this: How can I successfully pass a variable from @Input to a service in an Angular2 component? (Code has been simplified) This is my current component ...

Activate an iframe upon changing the media query

I am currently working on a webpage where I have included an image within an iframe. I am looking to change the content displayed inside the iframe based on different media query breakpoints. For instance, if the viewport has a minimum width of 900px, I ...

Choose an element at random

I am trying to figure out how to select all div elements with the same class of "dot" under a parent div in JavaScript. Here is an example structure: <div id="dots"> <div class="dot"> . </div> <div class="dot"> . </div> ...

Jquery and prototype are at odds with each other

Currently utilizing prototype and jQuery in addition to implementing a slide with another plugin that also requires jQuery. I've attempted using jQuery.noConflict(), but unfortunately, it still isn't functioning properly. var $j = jQuery.noConf ...

What is the process for bundling a separate JavaScript file with Webpack5?

I am new to the world of webpack. I have 2 javascript files and I want to designate one as the main entry file. However, for the other file, I only want to include it in specific files. For example, looking at the file structure below, main.js is my entr ...

Is there a way to provide "only responsive" content to the mobile m. subdomain without the need for redirection?

I currently have a website with www. that redirects to different content on the mobile m. site. I am in the process of updating my site to be responsive, but I want to ensure that I do not lose the links to the m. site in Google SERP. How can I redirect m ...

A guide on resolving the 'Unexpected identifier array in JSON Parse Error' encountered during an AJAX Request

I'm currently working on setting up a Contact Form Validation and I require the variable $msg from a php script called 'sendEmail.php'. The actual mailing system is functional, as the script successfully receives form inputs from index.php a ...

Mastering the art of utilizing sequelize and promises effectively

I'm currently learning how to create apps using expressJS and Sequelize. I could really use some help as I'm more accustomed to sequential programming. My project involves two models: Todo (id, title) and TodoItem (id, content, complete, todoId). ...

eliminating labels from a string through recursive method

One of my challenges involves developing a function that can remove tags from an input string. For example: '<strong>hello <em>my name <strong>is</strong> </em></strong>' The desired result should be: &apos ...