Switching CSS styles - seeking a smoother integration

I have successfully implemented a JS CSS switcher, which works brilliantly. However, I would like it to function more seamlessly. When opening a new page on the site, the default CSS style sometimes flickers briefly before the selected CSS style is reapplied by the cookie.

For example, if the canvas style is the default and a user selects the corporate style, when they open another page on the site, the canvas style briefly shows before being replaced by the corporate style. This issue is more noticeable on older computers but does occur on Chrome and other browsers for me. Is there anyone with the expertise to update the script below to first check for the cookie and then apply the default style if no cookie is found, instead of seemingly applying the default style at the same time?

The code I am currently using is as follows:

In the HTML head:

<script type="text/javascript">
$(function()
    {
        // Call stylesheet init so that all stylesheet changing functions 
        // will work.
        $.stylesheetInit();

        // This code loops through the stylesheets when you click the link with 
        // an ID of "toggler" below.
        $('#toggler').bind(
            'click',
            function(e)
            {
                $.switcher();
                return false;
            }
        );

        // When one of the styleswitch links is clicked then switch the stylesheet to
        // the one matching the value of that link's rel attribute.
        $('.styleswitch').bind(
            'click',
            function(e)
            {
                $.stylesheetSwitch(this.getAttribute('rel'));
                return false;
            }
        );
    }
);
</script>






<link rel="stylesheet" type="text/css" href="/css/canvas.css " title="canvas">
<link rel="alternate stylesheet" type="text/css" href="/css/corporate.css " title="corporate">
<link rel="alternate stylesheet" type="text/css" href="/css/earth.css " title="earth">
<link rel="alternate stylesheet" type="text/css" href="/css/space-and-stars.css " title="space-and-stars">
<link rel="alternate stylesheet" type="text/css" href="/css/under-the-sea.css " title="under-the-sea">
<link rel="alternate stylesheet" type="text/css" href="/css/classical.css " title="classical">
<link rel="alternate stylesheet" type="text/css" href="/css/creative.css " title="creative">

The JavaScript part:

(function($)
    {
        // Local variables for toggle
        var availableStylesheets = [];
        var activeStylesheetIndex = 0;

        // To loop through available stylesheets
        $.switcher = function()
        {
            activeStylesheetIndex ++;
            activeStylesheetIndex %= availableStylesheets.length;
            $.stylesheetSwitch(availableStylesheets[activeStylesheetIndex]);
        };

        // To switch to a specific named stylesheet
        $.stylesheetSwitch = function(styleName)
        {
            $('link[@rel*=style][title]').each(
                function(i) 
                {
                    this.disabled = true;
                    if (this.getAttribute('title') == styleName) {
                        this.disabled = false;
                        activeStylesheetIndex = i;
                    }
                }
            );
            createCookie('style', styleName, 365);
        };

        // To initialise the stylesheet with it's 
        $.stylesheetInit = function()
        {
            $('link[rel*=style][title]').each(
                function(i) 
                {
                    availableStylesheets.push(this.getAttribute('title'));
                }
            );
            var c = readCookie('style');
            if (c) {
                $.stylesheetSwitch(c);
            }
        };
    }
)(jQuery);

// Cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
    var nameEQ = name + "=";
    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,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name)
{
    createCookie(name,"",-1);
}
// /cookie functions

Answer №1

In my opinion, the best approach would be to handle it on the server-side...

By the way, when you use

$(function()
{ 
});

jQuery will wait for the DOM to be fully loaded before executing the function.

Therefore, it is recommended to place the JavaScript code just below the <link /> tags, outside of the $(function(){}); statement. This will ensure that the script runs as soon as the browser parses it, and before the page is completely loaded (it should be positioned after the link elements because they need to be loaded first).

Answer №2

It is recommended to run your code before the DOM is ready, as waiting for jQuery's $(function(){...}) can cause flickering due to page loading delays.

For more insights, check out this link:

If you are experiencing issues with links not working, follow these debugging steps:

>>> $('link[@rel*=style][title]') --> confirms styles exist
[..., <link rel=​"alternate stylesheet" type=​"text/​css" href=​"/​css/​corporate.css " title=​"corporate">, ...]

>>> $.stylesheetSwitch('corporate') --> appears to be functioning correctly

The problem lies in the absence of onclick bindings on the links. Consider using this.getAttribute('title') instead of relying on rel="alternate stylesheet" for a unique theme identifier.

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

Using dynamic template URLs in resolving with Angular's UI-Router can provide flexibility

Currently, I have implemented a parent directive for an entire view to interchange templates based on the outcome of a promise. .directive('myDirective', function(myService) { var rootDir = '/path/to/templates'; return { ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

Save the selected value from the dropdown menu and automatically check the corresponding checkbox when it

I'm attempting to update the 'value' of a checkbox once an item is chosen from a dropdown list and then the checkbox itself is clicked. I have created a jQuery function that captures the value from the dropdown list (I omitted the code for t ...

Creating a standalone card using Bootstrap

Trying to create this... https://i.stack.imgur.com/PMRSI.png However, I'm unsure of how to achieve it. <div class="row justify-content-center"> <div class="col-3 me-3" style="background-color: #F1F3F8; border-r ...

Submitting an HTML form to a PHP file for processing before returning to the original HTML page for further interaction

I am looking to figure out how I can send a <FORM> from an HTML page to a PHP file that will retrieve data from a database and then return the results to the same HTML page without any redirection. What I aim for is to avoid redirecting users. Take ...

Struggling to Confirm Inaccuracies in Material UI Forms

Struggling to validate form errors in React with Material UI using JOI and running into issues. Even the console.log() results are not showing up in my validate function. The error display is also confusing. ... import React from "react"; import ...

Prevent unwanted bouncing and zooming on IOS10+ when using routing in VueJS

Currently, I am developing a Vue.js application that integrates with Three.js to display 3D models. I am using Vue.js with Vuetify as the framework and incorporating the Vue.js router. Due to the nature of displaying 3D models, I need to prevent zooming i ...

Reveal the table only once a search has been completed

Currently, I am in the process of developing a small project and my aim is to have the table with the results appear only upon clicking the button or initiating a search. If you are interested, you can view it at this link: . My objective is to keep the t ...

Create a full-width slider using Materialize CSS framework

When using materializecss to create a slider, I encountered an issue where the image is full width but not full height, causing scrollbars to appear. What changes can I make to ensure the slider fills out my screen without any scrollbars? Additionally, I ...

What is the process for converting a string literal into raw JSON and then storing it?

When trying to edit object values using a text input element and JSON.stringify(txt, null, 2), everything seems fine initially. However, after submitting the input, I end up with unwanted characters like "/n" and "\" within the string literal. Despite ...

Post your artwork on Facebook's timeline

I am working on a website that allows users to create custom smartphone cases. One feature I want to implement is the ability for users to share their design on Facebook, including the actual design itself. I have the object and the canvas with the 's ...

How can you enhance the visibility of AngularJS Materials dropdown menus?

While experimenting with AngularJS Materials, I noticed that the text in some elements like <md-input-container> and <md-select> may be too light for some people to read easily. I wanted to find a way to make the text more visible without chang ...

tapping on the division and sliding it to and fro

I am trying to achieve a functionality where clicking a div will move another div to the right by 0, and on clicking the div again, the second div will move to the right by -200. However, I am facing issues getting it to work properly. $(document).ready(f ...

javascript - convert a JSON string into an object without using quotation marks

Consider the following example: var mystring = `{ name: "hello", value: 1234 }` var jsonobj = JSON.parse(mystring) The code above will not output anything because the "name" and "value" keys are missing quotes. How can I parse this strin ...

Efficiently transferring a style property to a child component as a computed property in Vue.js

Currently, I am facing an issue that involves too much logic in my inline style, which I would like to move inside a computed property. While I understand that this is the correct approach, I am unsure of how to implement it. To provide a clearer understa ...

Encountering a Cypress testing issue linked to webpack. Feeling unsure about the next steps to address it

https://i.sstatic.net/z6bmW.png I encountered an error while attempting to run a test file that I created. The default tests run smoothly, but the error only occurs with the file I created. import {cypress as cy} from "cypress" describe('T ...

THREE.js : Chart Your Course in the Digital Realm

When I have a moving object controlled by code such as: dx = [not important]; dy = [not important]; dz = [not important]; d = new THREE.Vector3(dx, dy, dz); mesh.postion.add(d); How can I ensure that my mesh is facing the direction it's moving in? I ...

Hover effect on a single cell in a Bootstrap table

As I was working on creating a calendar design, I found myself pondering how to incorporate a hover effect using Bootstrap 4 for the cells. Here is a preview of the current calendar design I am aiming to achieve a hover effect similar to Bootstrap's ...

What is the process for excluding or removing an input once the PHP code has been run?

I am working on a project with a post input field where I submit simple data. <form method="post" action="result.php"> <input type="url" name="url" class="form-control" placeholder="http://example.com/"> <input type="submit" name="s ...

Checking validation with parsley.js without triggering form submission

I have been working with the latest release of Parsley for data validation. While it is validating my data correctly, I am encountering an issue where the form does not submit after validation is complete. I have spent hours trying to troubleshoot this pro ...