What is the best way to ensure jQuery loads before CSS code on a website

I am currently working on a blog project that allows visitors to customize the background color by simply clicking on one of five available buttons.

$(function(){

        //Checking if a color scheme has already been selected
        var chosenColor = parseInt(getCookie("background_color"));

        switch(chosenColor){
            case 1:
                $('body').css('background-color','#0A0A0A');
                break;
            case 2:
                $('body').css('background-color','#766777');
                break;
            case 3:
                $('body').css('background-color','#EEE6EE');
                break;
            case 4:
                $('body').css('background-color','#9F00A9');
                break;
            case 5:
                $('body').css('background-color','#420668');
                break;
            default:
                $('body').css('background-color','#9F00A9');
        }

        $('#cor_01').click(function(){
            setCookie('background_color', 1);
            $('body').css('background-color','#0A0A0A');
        });
        $('#cor_02').click(function(){
            setCookie('background_color', 2);
            $('body').css('background-color','#766777');
        });
        $('#cor_03').click(function(){
            setCookie('background_color', 3);
            $('body').css('background-color','#EEE6EE');
        });
        $('#cor_04').click(function(){
            setCookie('background_color', 4);
            $('body').css('background-color','#9F00A9');
        });
        $('#cor_05').click(function(){
            setCookie('background_color', 5);
            $('body').css('background-color','#420668');
        });
    });

The default color for the blog is purple.

background: #9F00A9

While the button event works perfectly when the user changes the background color, there is an issue when navigating between different pages on the blog. The previously selected color briefly reverts back to black before loading the correct color (for example, going from purple to black and then back to purple). To address this, how can I ensure that the user's selected color is loaded as the priority?

Answer №1

When looking at it this way, calling $(foo) (assuming that foo is a function) indicates to "wait until the document is completely loaded before executing foo". This precaution ensures that your HTMLElements are present and ready for use. However, if you shift the call to a <script> tag positioned after or within the Node, you can be confident that they exist by the time the code is triggered.

For instance, if your function solely relies on the <body> element, name it foo and proceed like this:

<body>
    <script type="text/javascript">
        foo();
    </script>
    <!-- remainder of body content -->
</body>

This approach will guarantee that it is called promptly, during a period when any potential errors have been minimized.

Answer №2

Consider this as your HTML code

 <body>
 <script>
 $( document ).ready(function() {
     //Ensuring that the page has fully loaded before calling the function
     backgroundColour(getCookie("cor_de_fundo"));
 });
 </script>
</body>

Here is the updated function you can use: function backgroundColour(cookie) {

    //Checking if a color scheme is already selected
    var chosenColor = parseInt(cookie);
    if(!chosenColor) {
        $('body').css('background-color','#9F00A9');
    }
    else {
    switch(chosenColor){
        case 1:
            $('body').css('background-color','#0A0A0A');
            break;
        case 2:
            $('body').css('background-color','#766777');
            break;
        case 3:
            $('body').css('background-color','#EEE6EE');
            break;
        case 4:
            $('body').css('background-color','#9F00A9');
            break;
        case 5:
            $('body').css('background-color','#420668');
            break;
    }

    $('#cor_01').click(function(){
        setCookie('cor_de_fundo', 1);
        $('body').css('background-color','#0A0A0A');
    });
    $('#cor_02').click(function(){
        setCookie('cor_de_fundo', 2);
        $('body').css('background-color','#766777');
    });
    $('#cor_03').click(function(){
        setCookie('cor_de_fundo', 3);
        $('body').css('background-color','#EEE6EE');
    });
    $('#cor_04').click(function(){
        setCookie('cor_de_fundo', 4);
        $('body').css('background-color','#9F00A9');
    });
    $('#cor_05').click(function(){
        setCookie('cor_de_fundo', 5);
        $('body').css('background-color','#420668');
    });
});

Update: I recommend placing this code in the head tag, below the stylesheet:

<script>
if (getCookie("cor_de_fundo")) {
$('body').css('background','url("http://4.bp.blogspot.com/-SZodpKgdjwk/UkCj20gd4XI/AAAAAAAADZk/tIAmBbkoecU/s1600/square_bg.png") repeat');
}
</script>

This way, if a cookie is set, you will have dots on the background without the purple color. This should prevent the issue from happening.

Your current logic seems to be incorrect.

Instead of saying "use a purple background with dots and then change the color if there is a cookie," try saying "if there is a cookie, use a color with dots, otherwise use a purple background with dots."

Currently, you are setting a purple background with dots initially, then changing it if there is a cookie present.

Answer №3

It seems like you're interested in using the history API to avoid reloading the entire page, right?

You can check out some examples that demonstrate no need for page reloads:

Answer №4

Have you experimented with using local storage to store the background color settings?

$(function(){
 if(localStorage.bgcolor==undefined)
    localStorage.bgcolor="white" //default color that appears first time

 $('body').css('background-color',localStorage.bgcolor);

   $('#cor_01').click(function(){
     localStorage.bgcolor = "#0A0A0A";
     $('body').css('background-color',localStorage.bgcolor);
   });
   $('#cor_02').click(function(){
     localStorage.bgcolor = "#766777"
     $('body').css('background-color',localStorage.bgcolor);
   });
   // additional code can be added for more button functionalities
});

Explore HTML5 local storage

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

"Resolving an inconsistency problem with the Vary header in Htaccess

Could someone help me identify the issues in my htaccess code? I'm encountering errors: This response is negotiated, but doesn't have an appropriate Vary header. The resource doesn't send Vary consistently. ## add vary header <IfModule ...

How to properly center and align the width of a figcaption element within an image placed in a figure element

I've been struggling for two days now trying to fix an issue with the alignment of images and captions on my Django application. In my app, users can upload images, and I'm using figure and figcaption tags to display the image with a caption. Ho ...

Creating a function to limit the display value of Material UI Autocomplete similar to Material UI Multiple Select's renderValue

Incorporating Material UI Features Utilizing the Material UI Multiple Select, you have the ability to truncate the displayed value after selection instead of wrapping onto another line by setting the renderValue to .join for the selected options, enabling ...

What's the best way to layer a fixed div over an absolutely positioned div?

I am in the process of developing a small web application. In this project, I have two div elements - one is set to absolute positioning and the other to static positioning. My goal is to position the static div on top of the absolute div, ensuring that it ...

Extend the width of a div element to fit the size of its absolutely positioned

I am facing an issue with a Div that contains multiple absolutely positioned divs. The clickable area of the main div expands to cover the children, but the drawn area does not. I need the drawn area to encompass all the container divs. You can view a JSF ...

Mastering the Art of Writing an Ajax Post Request

I am attempting to transmit an image URL to a node.js server from some JavaScript using the Ajax POST method. My expectation is for the server to respond with some text, but I'm encountering issues and unsure where the problem lies. Below is the relev ...

Attempting to implement form validation on my website

Recently watched a tutorial on basic form validation on YouTube, but I'm encountering an issue where the error messages from my JavaScript file are not displaying on the website during testing. I have set up the code to show error messages above the l ...

Utilizing numerous await statements within a single asynchronous function

My async function has 3 awaits, like this: const sequenceOfCalls = async(req, res, next) =>{ await mongoQuery(); await apiCall1(); await apiCall2(); } apiCall1 uses response of mongoQuery and apiCall2 uses response of apiCall1. The issue is ...

Removing a SubDocument from an Array in Mongoose

For my project, I am utilizing mongoose to create a database. The schema for my Class looks like this: const mongoose = require('mongoose') const classSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, consultant: { type: mo ...

Avoiding the "urls" format using the onBeforeRequest function

chrome.webRequest.onBeforeRequest.addListener(function(details) { if (localStorage.on == '1') { return {cancel:true}; } }, {urls: ["*://*.domain1.net/*","*://*.domain2.com/*","*://*.domain3.com/*"], types: ["script","xmlhttpreques ...

I am unable to switch my carousel to full-screen mode

I'm struggling to make the carousel fullscreen even though I've set the width to 100%. Bootstrap was used in this project. Any help would be appreciated. Thank you! <html> <head> <link href="homepage.cs ...

Having trouble with implementing ng-hide and ng-show functionality

I have been working on creating my very first Angular website and so far, everything has been going smoothly with the first page. However, I am facing an issue with the second page not appearing as expected when it meets the condition set with ng-show in t ...

Scroll a div using JavaScript/jQuery

I'm currently facing some challenges in resolving this issue. My goal is to pan a DIV using jQuery. The process is quite straightforward - on mouseDown, I capture X & Y coordinates and then subtract them from the newly obtained X & Y values during mou ...

"Step-by-step guide on incorporating and executing a jQuery function, along with integrating it into PHP code for seamless

I recently created a function to manipulate form fields using jQuery: (function () { jQuery.fn.field = function (inputName, value) { if (typeof inputName !== "string") return false; var $inputElement = jQuery(this).fin ...

How to submit form data with a POST request in Flask using fetch without having to reload

Despite reading numerous similar questions, I am still unable to determine how to achieve my goal. I have multiple forms on a single page and I am trying to submit data from each form without refreshing the page. Below is an example of one of the five form ...

"An error occurred while trying to access the data for a new user on the snapshot object while navigating to the screen. It seems that the object is

When I navigate to the screen, I use componentDidMount to trigger fetchNewUser which is meant to detect a new user and update it if necessary. However, I encounter an issue where on initial navigation to the screen, it returns undefined is not an object ...

How to eliminate escape characters in Jquery Post requests

I've come across several questions similar to mine, but I haven't found a satisfactory answer yet. My issue is as follows: I'm trying to convert a JQuery object into a Json String and then send this string to a PHP webpage. The sending part ...

Switching the typeface within the content data

Recently, I incorporated this code: <div data-content="Reach" class="main-image"> along with the following CSS styling: .main-image:before { content: attr(data-content); I am now wondering if there is a method to adjust the font size and ...

I'm having trouble getting Jquery's insertAfter() function to function properly

After creating a parent div and using jQuery's insertAfter() method to insert additional divs, an unexpected issue arises. The first record goes to the bottom, while subsequent records are inserted above it. Below is the function in question: functi ...

In Javascript, create a variable that dynamically updates for every child element

While this might appear to be a simple question, it has been troubling me for some time now. Let me elaborate on what I am trying to accomplish. I have a collection of images in a gallery, and my goal is to center each image vertically within its contain ...