`Uniform background color across all pages`

My goal is to allow customers to select a color that will persist across different pages on the website. The code below shows how users can choose a color on the first page:


    <select id="color" style="width: 5%; height: 10%" size="5">
        <option value="white">White</option>
        <option value="red">Red</option>
        <option value="yellow">Yellow</option>
        <option value="blue">Blue</option>
        <option value="green">Green</option>
    </select>

    <script>
       document.getElementById("color").onchange = function () {
           document.body.style.background = this.options[this.selectedIndex].value;
       }
    </script>

Answer â„–1

One way to achieve color persistence in your web app is by utilizing localStorage:

document.querySelector('#color').addEventListener('change', function () {
  document.body.style.background = this.value;
  localStorage.setItem('appColor', this.value);
});

document.body.style.background= localStorage.getItem('appColor');

Check out this Fiddle. Whenever you select a color, it will be saved for future use as the default color.

Additionally, you can streamline the code like so:

this.options[this.selectedIndex].value;

… simply becomes:

this.value;

Answer â„–2

Here is the recommended script for your webpage:

<body onload="OnLoad()">
    <select id="color" style="width: 5%; height: 10%" size="5">
       <option value="white">White</option>
       <option value="red">Red</option>
       <option value="yellow">Yellow</option>
       <option value="blue">Blue</option>
       <option value="green">Green</option>
   </select>

   <script>
    function OnLoad() {
        document.getElementById("color").onchange = function () {
            document.body.style.background = this.options[this.selectedIndex].value;
            document.cookie="WebBackgroundColor=" + this.options[this.selectedIndex].value;
        }
        var color = getCookie("WebBackgroundColor");
        document.body.style.background = color;
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
        }
        return "";
    }
    </script>
</body>

If you want to use this script on other pages, remember to change the body tag from <body> to <body onload="OnLoad()">.

Additionally, make sure to include the script code at the bottom or in the header of the page:

   <script>
    function OnLoad() {
        document.getElementById("color").onchange = function () {
            document.body.style.background = this.options[this.selectedIndex].value;
            document.cookie="WebBackgroundColor=" + this.options[this.selectedIndex].value;
        }
        var color = getCookie("WebBackgroundColor");
        document.body.style.background = color;
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
        }
        return "";
    }
    </script>

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

error in URI (not a valid URI):

Encountering an issue with a URI that is triggering a bad URI error. http://localhost:3000/api/v1/company_donations.json?token=foo&donation={&amount=101}&comment=Ordered The goal is to have the URL carry 2 attributes Token Donation obje ...

What is the best way to translate this code into JQuery ajax?

I have some code here that is currently using Javascript AJAX. I'm interested in converting it into jQuery AJAX, can someone help me with this? var mine = new XMLHttpRequest(); mine.onreadystatechange = function() { if (mine.readyState == 4 &am ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

What is the best way to link styleUrls to a CSS file located in a different directory?

I am trying to include the CSS file src/app/shared/layouts/admin/admin.component.css in my component located at src/app/admin/create-company/create-company.component.ts How can I properly reference this css file in the styleUrls of create-company.componen ...

Leveraging various routes to access data with a shared VueJS 3 component

Could you please review this code snippet: It displays two routes that utilize the same component to fetch content from an API. Main.js const router = createRouter({ history: createWebHistory(), routes: [ { path: "/route1& ...

What's the issue with the addClass function not working as expected?

I am currently integrating the website's navbar using PHP, which is why I am unable to use class="active" to highlight the active tab on my navigation bar individually. To solve this issue, I attempted to add the active class to the corresponding tab ...

Troubleshooting the malfunctioning Asp.net Ajax PageMethods

I recently decided to add ajax functionality to a project that didn't originally use it. To achieve this, I installed the ajaxToolkit and replaced the web.config content with that of a website already enabled with ajax features. Additionally, I includ ...

Tips on utilizing setInterval in a Vue component

When defining the timer in each individual my-progress, I use it to update the value of view. However, the console shows that the value of the constant changes while the value of the view remains unchanged. How can I modify the timer to successfully change ...

Exploring the behavior of Object.assign in for loops and forEach loops

I've come across an interesting anomaly with Object.assign in the following scenario. function sampleFunction(index, myList) { myList.forEach((element, i) => { if (i === index) { console.log(Object.assign({}, {"newKey": " ...

Creating a dynamic table with columns of fixed width in Angular on the fly

I am struggling to create a data table with fixed column widths (20% each). I have incorporated div elements in my table structure to enable dynamic row creation using Angular, but this has caused some design issues. My goal is for all rows to occupy 100% ...

Is there a way to use setTimeout in JavaScript to temporarily stop a map or loop over an array?

data.forEach((d, i) => { setTimeout(() => { drawCanvas(canvasRef, d); }, 1000 * i); }); I have implemented a loop on an array using forEach with a one-second delay. Now I am looking to incorporate a pause and resume f ...

What is the correct method of implementing the "OnChange" event to a WooCommerce select element?

My task is to include the onchange="myFunction()" in the select menu below. However, because the select menu is part of woocommerce, I want to ensure that the onchange="myFunction()" remains intact even after updating my theme. How can I achieve this goal ...

When applying styles in Polymer, it's important to take into account the width and height

Having trouble setting the width of elements within container elements in Polymer. Here's a simple example that illustrates the issue: <!doctype html> <html> <head> <base href="https://polygit.org/polymer+:master/webcomponent ...

Ensure that buttons are cropped when extending beyond the border of another DIV

My issue involves a main DIV with buttons contained within it. I am seeking a solution to ensure that the buttons are cut off at the edge of the DIV, similar to the concept illustrated in this image. In the image, the blue represents the body, the light gr ...

Learn how to store the outcomes of an HTTP operation within array.map() in JavaScript

Having read numerous articles, I am a complete beginner when it comes to async programming and struggling to grasp its concepts. My goal is to map a filtered array of objects and return the result of a function (an amount) to set as the value of pmtdue. De ...

Creating a Modal in React without the need for a button to trigger it

I am working on implementing a model using the React Material UI library to display information on the landing page when a user logs in. However, I am facing an issue with closing the modal once it appears despite using a timeout trigger. const[post,setP ...

I am experiencing difficulty with aligning my input boxes to the center in my React-Native

Just a heads up, this is my first time diving into the world of React Native, so bear with me as I try to figure things out. Please be kind if my question seems silly... Here's a snapshot of what I currently have: https://i.stack.imgur.com/VWGFm.png ...

Can the <article> tag and all its content be positioned in the center of the webpage?

Can the <article> and its content remain centrally aligned on the page? Check out my website here: Typically, when you visit a website, the article is positioned in the center of the page. However, in my case, the article only remains centered when ...

Struggling to retrieve scope data within directive from controller in AngularJS

As a newcomer to AngularJS, I have utilized a service to retrieve data from the backend and received it in the controller. Now, my task is to parse these values and dynamically generate elements in a directive. However, when attempting to do so, I am encou ...

Master the art of fetching response data from an API and implementing a function to process the data and generate desired outputs using Node.js and JavaScript

Being new to node.js, javascript, and vue, I attempted to create a Currency Converter by fetching data from an API for exchange rates and performing calculations in a function. Despite successfully obtaining the exchange rates from the selected country in ...