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

What is the best way to create CSS rules that can be dynamically applied as classes using JavaScript?

I have been attempting to use the addClass function in JavaScript to add a class, but I am struggling to make it work. Is there a specific way to define a class that will be added to an element when clicked on? Here is what I have attempted: var input = ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

The following error occurred: Next Auth TypeError: URL is not valid

Every time I run my Nextjs project, I keep encountering an issue related to Next Auth. Despite using version 4.3.1, I am unsure about how to resolve it. Any assistance with next-auth would be greatly appreciated. Although I attempted to update my next-aut ...

Determine the file format using fs module in Node.js

I have a question about extracting file types or extensions from a folder. I have multiple files in a folder, and I want to retrieve the type/extension of the file that matches a randomly generated number stored in my num variable. Is there a way to achiev ...

What is the best way to send the article id to the pagination page using Ajax?

I am currently working on implementing a pagination system for a category result page that displays articles using AJAX. I am utilizing a WHERE clause and need to send the article ID to the AJAX page. Here are my code snippets: include_once '../db.ph ...

What could be causing the issue with the width: 100% not rendering correctly in this

I'm currently working on my footer, but I'm having trouble getting the width: 100% tag to work correctly. Here's a screenshot of what I mean: http://gyazo.com/9c23897cd7b9a74ca55ee9fb977f810c This is my CSS code: /*..Portfolio - Lars Beut ...

Top pick for building drag-and-drop web applications: the ultimate JavaScript library

Up to this point, I've relied on jQuery UI's draggables and droppables for my projects. However, I recently came across ExtJS and other libraries that caught my interest. I am aiming to create a professional-grade plugin. Can anyone suggest the b ...

Creating an HTML table that automatically generates sub rows dynamically

Looking to provide users with the ability to construct a table where they can create expressions. For example, in the expression shown below (((c1 A/O c2) A/O C3) A/O C4), where A/O represents 'And' and 'Or' conditions selected by the u ...

Retrieving form parameters within an EJS template

Hey there! I'm diving into the world of Node.js on my own and hitting a stumbling block that seems simple but is causing me some serious frustration. Despite countless searches on Google, I can't seem to figure it out due to fatigue setting in. I ...

`Look up values from specified key names`

Consider the following JSON data: const information = { "item1":1, "item2":20, "item3":123, "item4":[{"a":"apple","b":"ball"}], "item5":1211 } In ...

Using the <a> tag within a PHP script

Within my PHP code, I utilized the tag. However, when testing the code, the output appeared as a link but was not clickable. $data1 = mysql_query("SELECT * FROM image_upload INNER JOIN user_table ON image_upload.user_id=user_table.user_id WHERE flag=1 ORD ...

Assistance with the Chakra UI Range Slider in React

I could use some help figuring out where exactly to implement my OnChange and Map functions for mapping JSON data into a Range Slider. Everything seems to be rendering correctly, but I keep encountering an error when I try to move the slider: Unhandled Ru ...

If the font size exceeds a certain value in SCSS, then apply a different value

Can SCSS handle this scenario? I am looking to set the font size to 22px in case it is greater than 30px, especially within a media query for a max width of 480px. ...

Unlimited scrolling feature on a pre-filled div container

Looking for a way to implement infinite scroll on a div with a large amount of data but struggling to find the right solution? I've tried various jQuery scripts like JScroll, MetaFizzy Infinite Scroll, and more that I found through Google search. Whi ...

Is there a minimum height restriction for v-select in Vuetify.js?

Looking at the code snippet provided below, I am facing an issue while trying to decrease the height of a v-select element. It seems like there is a minimum limit set for the height, as reducing it beyond height = 40 doesn't have any effect. Is there ...

Is there a way for my component to function seamlessly within another component without the need for redundant code?

Is there a way to avoid repeating code when using my component inside another component? For example, in the file NextPage.js, the <LogoutButton/> component does not perform its function. How can I ensure that the <LogoutButton/> behaves the s ...

The JQxTreeGrid is displaying properly, however, it is not loading the data from the JSON source

Looking for some assistance with loading Json data into a Jquery grid using jqxTreegrid. Currently, the grid is displaying but not the data. Despite no errors in the debugger, I'm unable to figure out the issue. Any help resolving this matter would be ...

Navigating to the most recent item within ng-repeat (AngularJS or JavaScript)

I am working on a feature where posts are displayed using ng-repeat in a div, and users can enter new posts in an input box. The posts are sorted so that the latest one appears at the bottom. After adding a new post, I want to automatically scroll down t ...

Question inquired regarding a specific line of code in Javascript/Angular

While working in a factory, I am tasked with constructing an HTML page that includes a form. To successfully manipulate the form, I need to access the FormController. After conducting some research online, I managed to achieve my goal using the following l ...

Is there a way for me to access a user control property directly from the client side?

I'm in the process of developing several user controls that will be derived from my base class, BaseControl, which is a subclass of UserControl. The BaseControl class contains important features that I will need to utilize, including a string property ...