Utilize local storage to dynamically update the background color of a div section

Struggling to create a functionality on my website where users can input a color, save it to localStorage, and have a specific div's background set to that color across all pages. The main content div (with the same ID) needs to display this color consistently.

Here is the current code I have:

Jquery:

    if (typeof (localStorage) == 'undefined') {
    document.getElementById("result").innerHTML = 
'Your browser does not support HTML5 localStorage. Try upgrading.';
} else {
    if (localStorage.getItem("background") !== null) {
        getColour = localStorage.background;
        $("#content").addClass(getColour);
    }
}
console.log(localStorage);


$(document).ready(function () {
    getColour = localStorage.background;
    $('.palette').click(function () {
        getColour = localStorage.background;
        $("#content").removeClass(getColour);
        localStorage.removeItem('background');
        var setColour = $(this).attr("id");
        $("#content").addClass(setColour);
        localStorage.setItem("background", setColour);
    });
});

HTML

<div id="colours">
    <div id="colorPicker1" class="palette colorPicker1"></div>
    <div id="colorPicker2" class="palette colorPicker2"></div>
    <div id="colorPicker3" class="palette colorPicker3"></div>
    <div id="colorPicker4" class="palette colorPicker4"></div>
    <div id="colorPicker5" class="palette colorPicker5"></div>
    <div id="result"></div>
</div>
    <div id="content"></div>

CSS

#content{
    text-align:justify;
    position:relative;
    margin:45px auto 0px auto;
    width:85%;
    height:100%;
    border-radius:25px;
    padding: 10px 10px 10px 10px;
    z-index:1;
    border:1px solid black;
}
.palette {
    cursor: pointer;
    height: 18px;
    width: 18px;
    border: 2px solid #000
}

.colorPicker1 {
    background: /*#e1ffff;*/none;
}
#colorPicker1 {
    position:fixed;
    top:15px;
    left:15px;
}
.colorPicker2 {
    background: #ffffb8;
}
#colorPicker2 {
    position:fixed;
    top:15px;
    left:40px;
}

.colorPicker3 {
    background: #ffc5ff;
}
#colorPicker3 {
    position:fixed;
    top:15px;
    left:60px;
}

.colorPicker4 {
    background-color: #99ff9c;
}
#colorPicker4 {
    position:fixed;
    top:15px;
    left:90px;
}

.colorPicker5 {
    background: #97acff;
}
#colorPicker5 {
    position:fixed;
    top:15px;
    left:125px;
}

#colours {
    position:relative;
    height:30px;
    width:100%;
    border:1px solid red;
}

I am relatively new to web development, currently working on a university assignment. Trying to incorporate accessibility features into the site by allowing users to change the background color for easier reading. While I've managed to store and display the chosen color using localStorage, the issue arises when switching between pages as the color resets. I have the script running on each page locally.

Any assistance would be highly appreciated!

Thanks,

Blinky

Answer №1

Relocate


    if (typeof (localStorage) == 'undefined') {
    document.getElementById("result").innerHTML = 
'Your browser does not support HTML5 localStorage. Try upgrading.';
} else {
    if (localStorage.getItem("background") !== null) {
        getColour = localStorage.background;
        $("#content").addClass(getColour);
    }
}

Move this code into the document.ready function. Currently, you are attempting to apply a class to an element before it has been fully rendered.

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

Challenge involving CSS and Javascript for solving puzzles

In my attempt to create a puzzle with 2 rows and 3 columns using CSS and JavaScript, I envision the pieces of the puzzle being black and cut into various shapes. The objective is for users to drag these pieces onto the board in order to complete it. I have ...

What could be the reason for the malfunction of Bootstrap Js in my template?

This question focuses on understanding how something works rather than just fixing it. I really enjoy learning about this. Currently, I am involved in a project that combines VueJS and Symfony. One of the things I would like to achieve is using Bootstrap ...

How to utilize the index in a foreach loop as a variable in JavaScript

I am facing an issue with using the index of a forEach loop to access an array index in my code. It seems to work when I use a number directly, but not when I try to use the index variable. Any suggestions or insights on how to resolve this? let post ...

Exploring the functionality of componentWillReceiveProps within functional components

Embarking on my journey with functional components after extensively working with class components. While experimenting, I encountered a challenge: how can I incorporate the functionality of componentWillReceiveProps within the context of the useEffect h ...

Guidance on modifying a sub row within a main row in Sails.js

I am currently working on a sails.js application This is the model structure for my application: name: String, address:String, appSettings: { header: String, color : String, font: String, } In my development process, I have utilized independ ...

The system encountered an error while trying to access the property 'enabled' of an undefined object

When working on a reactive form in my code, I need to ensure the values are properly set for the controls. ngDoCheck() { setControlValues(); } ngChanges(changes: SimpleChanges): void { setControlValues(); } private setControlValues() { try { ...

switch out asterisk on innerhtml using javascript

Is there a way to replace the asterisks with a blank ("") in the innerHTML using JavaScript? I've attempted this method: document.getElementById("lab").innerHTML = document.getElementById("lab").innerHTML.replace(/&#42;/g, ''); I also ...

The color of the link remains blue when using Firefox

Check out my website at kenastonchiropractic.com When viewing the site in Chrome, the "Home" link remains the same color as the other links and they all turn white when hovered over. However, in Firefox, the "Home" link stays blue even after being clicked ...

Conceal a table row (tr) from a data table following deletion using ajax in the CodeIgniter

I am attempting to remove a record in codeigniter using an ajax call. The delete function is functioning correctly, but I am having trouble hiding the row after deletion. I am utilizing bootstrap data table in my view. <script> function remove_car ...

revealing and concealing content using jquery

Just starting out in programming but eager to learn.. I'm looking to implement a show/hide feature for div elements using jQuery. I currently have two <div> elements, 1. <div class="div1"> 2. <div class="div2"> ----> set to hi ...

jQuery prioritizes enforcing style over using a CSS file

I am facing an issue with a nested div functioning similar to a drop-down menu. The problem arises when I click on the #two div as I want it to disappear. To handle this, I utilized jQuery and tried using both .hide() and .slideUp(). However, upon implem ...

When using ng-repeat with an array, not all array values are repeated

I have a basic angular block that looks like this <script> function simpleList($scope){ $scope.addItem = function(){ $scope.items.push($scope.newItem); } $scope.items = ["apple", " ...

The behavior of the input in React-bootstrap-daterangepicker is acting strangely

I'm encountering an issue while trying to integrate react-bootstrap-datepicker with input fields. The problem arises when I click on one of the inputs or press a key, causing the calendar to toggle (showing if hidden and vice versa). To reproduce this ...

When I click on something else, the dropdown doesn't automatically close

In my current setup, I have 3 dropdowns on the page. When I click outside of any dropdown, they are correctly closed. However, if one dropdown is already open and I click on another one, the previously opened dropdown remains open. I want all dropdowns to ...

Bot on Discord using Discord.Js that generates unique invites for users

I'm trying to find a way to generate an invite link for users to keep track of invites. The code I have currently is creating the invite for the Bot instead. const channel = client.channels.cache.find(channel => channel.id === config.server.channel ...

What is the best way to bridge the gap between the rows?

After combining the top and bottom blocks, I now have a gap in my layout. Is there a way to move this row up without causing any issues? I need assistance with resolving this problem using Bootstrap. <link rel="stylesheet" href="https://maxcdn.boots ...

The jQuery Input Box Autocomplete Feature

After creating an autocomplete box using jQuery and PHP to fetch data from the database, I encountered a slight issue. Everything works fine except that when I start typing in the input box, it retrieves all results instead of only those similar to what I ...

Can you explain the ratio between 1 unit in Three.js and 1 unit in Oimo.js?

When using Three.js to create objects and combining it with a physics system like oimo.js, I've noticed that each system has its own sizing method. While Three.js has its own sizing system for object creation, oimo.js uses a different sizing system sp ...

"Exploring the Interaction Between Solr, Tomcat, and CORS

Currently, I have Solr 4.3 running on Apache Tomcat 9 as a webapp for a CRM product to provide indexes. To perform a search on the indexes, I am querying Solr using the following URL: http://localhost:8888/solr-intranet-int/intranet_users/suggest?q=(surn ...

What is preventing this jQuery from appending text to the div?

$("#btn-id").click(function() { $.getJSON('employee.json', function(response, status) { if (status == "error") $('#err-id').text('Error Message: Not found'); }); }); <!DOCTYPE html> <html> <body& ...