Is it possible for the background color to change in a sequence every time the page

I'm having trouble figuring out how to create a sequence that changes the background color every time the page is refreshed. I'm comfortable with basic HTML but not so much with JavaScript or CSS. I'm working on a page where I want the background to change along with some images, and I've managed to code the image sequence on refresh, but I'm struggling with achieving similar results for the background. Here's the code I have for the images:

    <script type="text/javascript">

            function loadNextImage1() {
                //get image object
                var myImg = document.getElementById('ImageRefresh');

                //declare image directory path and image array
                var thePath = "http://";
                var theImages = new Array();
                theImages[0] = "url";
                theImages[1] = "url";
                theImages[2] = "url";

                //get current cookie value
                var currentIndex = parseInt(getCookie());
                var imgPath = thePath + theImages[currentIndex];
                myImg.src = imgPath;

                //set next cookie index
                currentIndex += 1;
                if(currentIndex > (theImages.length - 1)) {
                    currentIndex = 0;
                }
                setCookie(currentIndex);
            }

            function setCookie(someint) {
                var now = new Date();
                var addDays = now.getDate() + 7
                now.setDate(addDays); // cookie expires in 7 days
                var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
                document.cookie = theString;
            }

            function getCookie() {
                var output = "0";
                if(document.cookie.length > 0) {
                    var temp = unescape(document.cookie);
                    temp = temp.split(';');
                    for(var i = 0; i < temp.length; i++) {
                        if(temp[i].indexOf('imgID') != -1) {
                            temp = temp[i].split('=');
                            output = temp.pop();
                            break;
                        }
                    }
                }
                return output;
            }
</script>

<body onload="loadNextImage1();">

<img id="ImageRefresh">

I'm hoping to find a way to make the background change on refresh as well. I thought about using a picture as the background color, but I can't assign an img id to the head. If this is a simple task, please bear with me as a lot of this is unfamiliar to me.

EDIT: Here's my current code for a background color changer that interrupts the sequence:

<script type="text/javascript>

            function loadNextImage1() {
                //get image object
                var myImg = document.getElementById('Sidebar1');

                //declare image directory path and image array
                var thePath = "http://";
                var theImages = new Array();
                theImages[0] = "URL";
                theImages[1] = "URL";
                theImages[2] = "URL";

                //get current cookie value
                var currentIndex = parseInt(getCookie());
                var imgPath = thePath + theImages[currentIndex];
                myImg.src = imgPath;

                //set next cookie index
                currentIndex += 1;
                if(currentIndex > (theImages.length - 1)) {
                    currentIndex = 0;
                }
                setCookie(currentIndex);
            }

            function setCookie(someint) {
                var now = new Date();
                var addDays = now.getDate() + 7
                now.setDate(addDays); // cookie expires in 7 days
                var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
                document.cookie = theString;
            }

            function getCookie() {
                var output = "0";
                if(document.cookie.length > 0) {
                    var temp = unescape(document.cookie);
                    temp = temp.split(';');
                    for(var i = 0; i < temp.length; i++) {
                        if(temp[i].indexOf('imgID') != -1) {
                            temp = temp[i].split('=');
                            output = temp.pop();
                            break;
                        }
                    }
                }
                return output;
            }
</script>

<script type="text/javascript>

            function loadNextImage2() {
                //get image object
                var myImg = document.getElementById('Sidebar2');

                //declare image directory path and image array
                var thePath = "https://";
                var theImages = new Array();
                theImages[0] = "URL";
                theImages[1] = "URL";
                theImages[2] = "URL";

                //get current cookie value
                var currentIndex = parseInt(getCookie());
                var imgPath = thePath + theImages[currentIndex];
                myImg.src = imgPath;

                //set next cookie index
                currentIndex += 1;
                if(currentIndex > (theImages.length - 1)) {
                    currentIndex = 0;
                }
                setCookie(currentIndex);
            }

            function setCookie(someint) {
                var now = new Date();
                var addDays = now.getDate() + 7
                now.setDate(addDays); // cookie expires in 7 days
                var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
                document.cookie = theString;
            }

            function getCookie() {
                var output = "0";
                if(document.cookie.length > 0) {
                    var temp = unescape(document.cookie);
                    temp = temp.split(';');
                    for(var i = 0; i < temp.length; i++) {
                        if(temp[i].indexOf('imgID') != -1) {
                            temp = temp[i].split('=');
                            output = temp.pop();
                            break;
                        }
                    }
                }
                return output;
            }
</script>

<script type="text/javascript>

            function changeColor() {

            //declare background colors array
            var colors = ["#00ffff", "#ff00ff", "ffff00"];
            colors[0] = "#00ffff";
            colors[1] = "#ff00ff";
            colors[2] = "#ffff00";

            //get current cookie value
            var currentIndex = parseInt(getCookie());
            var background = colors[currentIndex];

            document.body.style.backgroundColor = background;

            //set next cookie index
            currentIndex += 1;
            currentIndex %= colors.length;
            setCookie(currentIndex);
        }

        function setCookie(someint) {
            var now = new Date();
            var addDays = now.getDate() + 7
            now.setDate(addDays); // cookie expires in 7 days
            var theString = 'imgID=' + escape(someint) + ';expires=' + now.toUTCString();
            document.cookie = theString;
        }

        function getCookie() {
            var output = "0";
            if(document.cookie.length > 0) {
                var temp = unescape(document.cookie);
                temp = temp.split(';');
                for(var i = 0; i < temp.length; i++) {
                    if(temp[i].indexOf('imgID') != -1) {
                        temp = temp[i].split('=');
                        output = temp.pop();
                        break;
                    }
                }
            }
            return output;
        }

</script>

<body onload="loadNextImage1(); loadNextImage2(); changeColor();">

Answer №1

This updated script now changes the background color:

<script type="text/javascript">

            function loadNextBackground() {

            //declare array of background colors
            var bgColors = ["#eee", "#123123", "red"];

            //initialize current index as cookie value
            var currentIndex = parseInt(getCookie());
            var currentColor = bgColors[currentIndex];

            document.body.style.backgroundColor = currentColor;

            //update cookie index
            currentIndex += 1;
            currentIndex %= bgColors.length;
            setCookie(currentIndex);
        }

        function setCookie(index) {
            var expirationDate = new Date();
            var addDays = expirationDate.getDate() + 7;
            expirationDate.setDate(addDays); // cookie expires in 7 days
            var cookieString = 'bgColorIndex=' + escape(index) + ';expires=' + expirationDate.toUTCString();
            document.cookie = cookieString;
        }

        function getCookie() {
            var defaultValue = "0";
            if(document.cookie.length > 0) {
                var cookieArray = unescape(document.cookie).split(';');
                for(var i = 0; i < cookieArray.length; i++) {
                    if(cookieArray[i].indexOf('bgColorIndex') !== -1) {
                        var cookieValue = cookieArray[i].split('=');
                        defaultValue = cookieValue.pop();
                        break;
                    }
                }
            }
            return defaultValue;
        }

</script>

<body onload="loadNextBackground();">

<img id="ImageRefresh">

Answer №2

To store the index, you have the option of utilizing HTML5's localStorage (or sessionStorage for session persistence):

<script type="text/javascript">

    function loadNextImage() 
    {
        // Obtain the image object
        var myImage = document.getElementById('ImageRefresh');

        // Specify the image directory path and create an array for images
        var imagePath = "http://";
        var imageArray = new Array();
        imageArray[0] = "url";
        imageArray[1] = "url";
        imageArray[2] = "url";

        // Retrieve the stored index from localStorage (to be parsed later)
        var storedIndex = localStorage.getItem('backgroundImageIndex');

        // Handle cases where localStorage is empty
        var currentIndex = (storedIndex === null) ? 0 : JSON.parse(storedIndex);

        // Reset index to 0 if it exceeds the array length
        currentIndex = (currentIndex > 2) ? 0 : currentIndex;

        // Set the image source
        myImage.src = imagePath + imageArray[currentIndex];

        // Save the index to localStorage
        localStorage.setItem('backgroundImageIndex', JSON.stringify(currentIndex));
    }
</script>

<body onload="loadNextImage();>

<img id="ImageRefresh">

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

The text for the Google chart is nowhere to be found

After creating a test project using the Google Chart example, I noticed that some text from the chart is missing after adding CSS. Here is the CSS code I used: html, body { font-size: 100%; height: 100%; width: 100%; } body { background: ...

Enhance TinyMCE functionality to permit text as a primary element within <table> or <tr> tags

I've been struggling for the past three hours, trying out different solutions and searching like crazy on Google. Unfortunately, I have not been able to find a resolution to this particular issue. Issue: TinyMCE is not allowing me to insert text dire ...

How can I remove a row from an MVC webgrid using an ajax call?

Within my MVC Razor view, I have a partial view containing webgrid data. My goal is to include an action link to delete a specific row of data. To accomplish this, I crafted the following JavaScript function: function delMeal(pid) { if (confirm("Do yo ...

`A mistake occurred while building in the package.json file`

While attempting to run all build processes by using the command npm run build:css, I encountered an error indicated below. Even after running npm cache clean --force, the issue remains unresolved. https://i.sstatic.net/4edDo.png npm ERR! code ELIFECYCLE ...

Loading complex models with Three.js

Whenever I attempt to load a significantly large file utilizing the appropriate loaders provided by the library, the tab in which my website is running crashes. Despite trying to implement the Worker class, it doesn't seem to resolve the issue. Here i ...

Space within a series of photographs

Looking for some assistance: I am trying to maintain a consistent margin of 10px between posts and between photos in a photoset. However, when a post is a photoset, the margins of the bottom photo and the overall post add up to 20px. I want to retain the ...

What is the best way to create a dropdown menu within an iframe that appears on top of all other frames?

The code snippet below is from my frameset.jsp file: </head> <iframe width="100%" src="mail_frame.html"></iframe> <iframe width="105px" height="100%" src="sidenav.html" id="leftnav" name="leftnav" ></iframe> ...

I am facing difficulties displaying Arabic language characters on my HTML code

I created a website and included the following meta tag in the head section: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> However, all Arabic text appears distorted as shown in the image. Interestingly, when I manually cha ...

Is your pure function component not receiving or responding to input props correctly?

Here is my code snippet: const actionCreators = { action: AppReducer.actionCreators.action } interface GlobalState { user: Model.User | null; } interface InputState { setStashBarWidth(width: number); stashWidth: number; } const Header = ...

Step-by-step guide on integrating a custom JS file into an Angular component

Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something cru ...

I'm facing an issue with running npm start on my react project ever since I installed babel-cli

YTGJAI@DESKTOP-DOAIF41 MINGW64 ~/Desktop/LYNDA MERN/Exercise Files/Ch02/02_01/start/dist $ npm start [email protected] start c:\Users\mctumbaga\Desktop\LYNDA MERN\Exercise Files\Ch02\02_01\start httpster -d ...

A more efficient method for refreshing Discord Message Embeds using a MessageComponentInteraction collector to streamline updates

Currently, I am working on developing a horse race command for my discord bot using TypeScript. The code is functioning properly; however, there is an issue with updating an embed that displays the race and the participants. To ensure the update works co ...

What can I do to remove the hidden <p> tags that Wordpress is inserting into my HTML code?

There seems to be some extra space appearing between my divs (inside a main div) that is possibly due to unexpected <p> and </p> tags being added by WordPress. This issue is quite common with WP, but the problematic tags are hidden so I am unab ...

Creating an expo apk using eas buildWould you like a tool for generating

Following an update to Expo, the process of building apk files using expo build:android -t apk is no longer supported. Instead, it now recommends using eas builds with the command eas build -p android --profile preview. However, this resulted in building a ...

Removing Form Fields Utilizing Javascript

Is it possible to create a unique function in Javascript that automatically removes a form field if it remains unfilled? <form id="myform"> <label for="q1" id="q1label">question 1</label> <input type="text" id="q1" name="q1"/> < ...

Employing [style.something.px]="2" in Angular to specify the thickness of the border

Presently, I am setting the width of the element using this code format: <div [style.width.px]="size" [style.height.px]="size"></div> What I am aiming for is to utilize a comparable format but to define the border-width css attribute, such as ...

The custom font fails to load on a customized Material UI theme

In my React web application, I tried to implement a custom font by writing the following code: import React, { FunctionComponent } from 'react' import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles' import SofiaPro ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

Implementing a button on a polygon shape within an SVG

I have an SVG at the bottom and I would like to place a button on the bottom line that is also responsive. How can I achieve this using CSS? What I am trying to accomplish: Example Image Is it possible with just CSS and how should I go about implementin ...

What is the best way to pass the "getjson" capability from one function to another in a seamless manner?

Currently, I am dealing with a situation where a getjson call is used to retrieve a large amount of data. However, I find myself constantly having to check if the data is null or not. Here is an example: if (data.Height == "") { $(&ap ...