Tips for avoiding the selected color from changing when refreshing the browser

Excuse my English proficiency...

I have implemented a feature on my website that allows users to change the colors of the site based on their selection, and it is working well.

However, the issue I am facing is that when the browser window is refreshed, the default color scheme is displayed instead of the selected color. I would like the selected color to be retained even after a refresh.

Thank you in advance for your help!

I eagerly anticipate your response.

    function openNav() {
        document.getElementById("mySidenav").style.width = "270px";
    }
    
    // More JavaScript functions...
    
    .sidenav {
        // CSS styles for the side navigation bar
    }

    // More CSS styles...

  
<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      
      <!-- Include necessary libraries and scripts -->

    </head>
    <body>
      <div id="content">
            <div class="container-fluid">
                <div class="index_top">
                    <div class="container">
                        <div class="col-md-12 col-sm-12 col-xl-12 col-12 col-lg-12">
                            <div class="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
                                <p>
                                    <i class="fa fa-phone"></i> &nbsp; &nbsp;123456789
                                </p>
                            </div>
                           
                        </div>
                    </div>
                </div>
    
                <!-- Include logo and other elements -->
                 
                <span class="icon" onclick="openNav()">
                    <img src="images/tool.png" class="img-fluid" alt="open"/>
                </span>
    
    
              
    
            </div>
        </div>
    </body>
    </html>

Answer №1

Enhance the efficiency of your code by adding a class to the boxes. Below is the updated code for reference:
HTML

<div>
<div class="box" id="red"></div>
<div class="box" id="blue"></div>
<div class="box" id="green"></div>
<div class="box" id="yellow"></div>
<div class="box" id="gray"></div>
<div class="box" id="voilet"></div>
<div class="box" id="black"></div>
<div class="box" id="white"></div>
<div class="box" id="purple"></div>
<div class="clearfix"></div>
<p id="original">Show Original</p>
<p id="content-width">Low width</p>
</div>

Script

function openNav() {
document.getElementById("mySidenav").style.width = "270px";
}

function closeNav() {
   document.getElementById("mySidenav").style.width = "0";
}

$(document).ready(function () {
$(".index_top,.about-text,.navbar-dark .navbar-nav .nav-link:focus, .navbar-dark .navbar-nav .nav-link:hover, .navbar-dark .navbar-nav .active > .nav-link, .navbar-dark .navbar-nav .nav-link.active, .navbar-dark .navbar-nav .nav-link.show, .navbar-dark .navbar-nav .show > .nav-link,.navbar-dark .navbar-nav .nav-link:focus, .navbar-dark .navbar-nav .nav-link:hover, .navbar-dark .navbar-nav .active > .nav-link, .navbar-dark .navbar-nav .nav-link.active, .navbar-dark .navbar-nav .nav-link.show, .navbar-dark .navbar-nav .show > .nav-link").css("background-color", localStorage.getItem("default"));
$("#content-width").click(function () {
    $("#content").css({
        "width": "900px",
        "margin": "auto",
        "border": "1px solid #ddd",
        "background-color": "white"

    });
    $("#myMap").css({
        "width": "370px",
        "height": "300px",            

    });
    $(".navbar-expand-md .navbar-nav .nav-link").css({
        "padding-right": "2.6rem",
        "padding-left": "2.6rem"
    });
    $("body").css("background-color",localStorage.getItem("default"));
});
$("#original").click(function () {
    $(".index_top,.about-text,.navbar-dark .navbar-nav .nav-link:focus, .navbar-dark .navbar-nav .nav-link:hover, .navbar-dark .navbar-nav .active > .nav-link, .navbar-dark .navbar-nav .nav-link.active, .navbar-dark .navbar-nav .nav-link.show, .navbar-dark .navbar-nav .show > .nav-link,.navbar-dark .navbar-nav .nav-link:focus, .navbar-dark .navbar-nav .nav-link:hover, .navbar-dark .navbar-nav .active > .nav-link, .navbar-dark .navbar-nav .nav-link.active, .navbar-dark .navbar-nav .nav-link.show, .navbar-dark .navbar-nav .show > .nav-link").css("background-color", "#2a3637");
    $("#nav").css("border-bottom", "5px solid #2a3637");
    $("#logo_img").attr("src", "images/logo.png");
    $(".for-bold-text").css("color", "#2a3637");
    $("#content").css({
        "width": "auto",
        "margin": "auto",
        "border": "none",
        "background-color": "white"
    });
    $("#myMap").css({
        "width": "500px",
        "height": "400px",

    });
    $(".navbar-expand-md .navbar-nav .nav-link").css({
        "padding-right": "4.25rem",
        "padding-left": "4.25rem"
    });
    $("body").css("background-color", localStorage.getItem("default"));
});

$(".box").click(function () {
    var color = $(this).css("background-color");
    var image = "images/logo_"+$(this).attr("id");
   changeColor(image, color)
});



function changeColor(image, color){
    $(".index_top,.about-text,.navbar-dark .navbar-nav .nav-link:focus, .navbar-dark .navbar-nav .nav-link:hover, .navbar-dark .navbar-nav .active > .nav-link, .navbar-dark .navbar-nav .nav-link.active, .navbar-dark .navbar-nav .nav-link.show, .navbar-dark .navbar-nav .show > .nav-link,.navbar-dark .navbar-nav .nav-link:focus, .navbar-dark .navbar-nav .nav-link:hover, .navbar-dark .navbar-nav .active > .nav-link, .navbar-dark .navbar-nav .nav-link.active, .navbar-dark .navbar-nav .nav-link.show, .navbar-dark .navbar-nav .show > .nav-link").css("background-color", color);
     $("#nav").css("border-bottom-color", color);
     $("#logo_img").attr("src", image);
     $(".for-bold-text").css("color", color);  
    localStorage.setItem("default", color);     
}

});

Answer №2

To solve your issue, try removing the code inside your #color.click function.

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
}

$(document).ready(function () {
    $("#content-width").click(function () {
        $("#content").css({
            "width": "900px",
            "margin": "auto",
            "border": "1px solid #ddd",
            "background-color": "white"

Answer №3

Storing and retrieving values using local storage can be a useful feature for maintaining data on page refresh.

$("#red").click(function () {
       localStorage.setItem("color","red"); 
    });


  $(document).ready(function () {
    var color= localStorage.getItem("color");   //retrieve from local storage.
        $("#content-width").click(function () {
            $("#content").css({
                "color": color,    // utilizing the value stored in local storage. 
                "width": "900px",
                "margin": "auto",
                "border": "1px solid #ddd",
                "background-color": "white"

            });

I hope this explanation is helpful.

For further details, check out https://www.w3schools.com/jsref/prop_win_localstorage.asp

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

What's the best way to make sure an image and text are perfectly aligned on the

How can I align an image and text on the same line, as currently the a tag is higher than my text? Here is the HTML code: <div class="author-name"> <img class="article-author-img" src="{{ preload(asset('assets/st ...

Top method for displaying radio buttons as switchable buttons within a web form

I want to customize the appearance of my radio buttons on a form to make them look like toggle-able HTML buttons, similar to the examples shown in these Bootstrap examples. By using Flask, Bootstrap, and jinja2, I've successfully converted my radio bu ...

The button icon fails to display correctly on the iPhone X, despite appearing correctly in the DevTools

Recently, I designed a "Scroll to top" button for my application. During testing using Chrome and Safari DevTools, the button appeared correctly on all devices: https://i.sstatic.net/Apb8I.png However, upon opening it on an iPhone X, I noticed that the i ...

Creating an object and setting its prototype afterwards

While exploring examples and questions online about prototypal inheritance, I noticed that most of them involve assigning prototypes to constructor functions. One common pattern is shown in the code snippet below: Object.beget = function (o) { var F = ...

I am looking to specifically target and write to a particular line in a text file using PHP

What I am searching for: file.txt: Name: John email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcdefghij">[email protected]</a> Here is my code snippet: <?php $myFile = "file.txt"; $txt = &apos ...

Combine two pieces of data from a JSON object using Angular's ng-repeat

Trying to organize data from a separate array into one section of a table. The first JSON named "names" : [ { "name": "AAAAAA", "down": "False" }, { "name": "BBBBBB", "down": "Tru ...

Tips for transferring the input text box value to angularjs when clicking on the text box

Here is the HTML code snippet: <tr ng-repeat="c in client"> <td><input type="text" id="id" value="{{c.id}}" onclick="display();"></input></td> <td><input type="text" value="{{c.fname}}"></td> </ ...

Arrangement featuring two distinct types of tiles

Looking for a way to achieve this layout using just CSS or a combination of CSS and a little JS. Click on my avatar to see the reference image enlarged =) I've tried using floats and display options but haven't been successful. Take a look at htt ...

Trouble arises when attempting to convert HTML into a PDF format

Currently, I am developing a billing application using Sails.js, Angular, and ejs. Everything is going smoothly, but now I have a pressing need to save the HTML invoice as a PDF. After hours of searching on npmjs, I came across the html-pdf package. It wa ...

Displaying website content within a pop-up dialog box

Currently, I am delving into the world of AJAX calls using jQuery.get() to dynamically load website content onto my HTML page. However, I have some doubts about whether I am utilizing this command correctly. As an example, I am trying to fetch data from a ...

What is the best way to populate MongoDB with information retrieved from an external API?

Recently, I've been diving into the world of NodeJS with mongoose & mLab. As someone new to these technologies, I'm slowly piecing together my model. Here's what it looks like for now, with plans to expand the schema down the road. cons ...

What is the procedure for selecting an element based on its child containing specifically filtered text?

Imagine a webpage with the following elements: <div data-search="type1"> any HTML <!-- .click is a child of any level --> <span class="click" data-source="page1.html">blue</span> <!-- let's call it "click1 ...

Difficulty encountered while using React.js map function to access specific JSON data

I'm encountering an issue where I am unable to read data from a JSON file. After checking that the data is stored in the component state and logging it to the console once the component is mounted, I attempted to render the URL string from the JSON da ...

Wordpress team exhibition

Does anyone know how to create a Team showcase slider in Wordpress? I have been using slick slider, but I'm looking for a way to add team members easily through a plugin rather than manually. I found an image of what I want it to look like. Can any ...

What is the approach for incorporating JavaScript variables in Jade templates for writing inline CSS styles?

Struggling to inject CSS code dynamically? You're not alone. style(type='text/css') #header a#logo { background:url(constants.logo) no-repeat; } @media only screen and (-webkit-min-device-pixel-ratio: 1.5) { #header a#logo { ...

Issues with loading webpages and graphics using the 'href' and 'src' attributes

I'm struggling with setting up the correct paths for my website. When using 'href', I am encountering a 404 error on the Github pages, but everything works perfectly fine when developing on a live server. It's difficult to pinpoint wher ...

How can Symfony, Jquery, and Ajax work together to append elements to themselves?

I've implemented a jQuery function that dynamically adds rows of data from one table to another table for submission. Essentially, when a user selects an item or items (a row) in the initial table, it gets duplicated in a separate area where they can ...

Tips on viewing a PDF document directly in the browser instead of saving it to your device

I have a unique api that returns a json-object containing a link to a pdf { pdf_link: 'http://uniqueurl.com/logs.pdf' } My goal is to open this pdf in a separate browser tab when the user clicks on the file name. I attempted to use the url as a ...

"Could you please include some additional information in the provided prompt

Automating the Window: https://i.sstatic.net/CEKpH.png Issue: Our team recently implemented an authentication process for our staging environment, which requires additional steps during testing. I discovered that 'prompt()' cannot be easily capt ...

Retrieving the object ID of an Open Graph from a page's URL

Is there a way to obtain the Facebook Object ID associated with a page directly from the page itself? For instance, if I requested the Object ID 325186347604922, this is what I received: <pre> { "url": ".../ricetta-bigne_salati.htm", "type": " ...