Incorporating a cookie to enhance the style switch functionality of

I need help adding functionality to a single button on my site. My goal is to switch the style of the site to a high contrast version when the button is clicked (by appending the high_contrast.css stylesheet to the head). Currently, my code only changes the style for the current page and reverts back to the default style when navigating to another page. I believe the issue lies in me setting the variable highContrast every time. I would like to incorporate the query cookie plugin (https://github.com/carhartl/jquery-cookie) but am unsure how to implement it in this scenario.

This is the HTML

<div id="contrast-btn"><a href="#" rel="css/high-contrast.css">high contrast</a></div>

This is the script

$(document).ready(function(){
    var highContrast = false;
    $("#contrast-btn a").click(function () {
        if (!(highContrast)) {
            $('head').append('<link rel="stylesheet" href="css/high-contrast.css" type="text/css" id="hc_stylesheet"/>');
            highContrast = true;
        }       
        else {
            // remove the high-contrast style
            $("#hc_stylesheet").remove();
            highContrast = false;
        }
    });
});

Any assistance is greatly appreciated. Thank you!

Answer №1

To access and modify the value, you must use the cookie method:

$(document).ready(function(){
// Function to add stylesheet
function appendStyleSheet() {
  $('head').append('<link rel="stylesheet" href="css/high-contrast.css" type="text/css" id="hc_stylesheet"/>'); 
}
// Add the style sheet if the cookie is set to true
if ($.cookie('high_contrast') == 'true') {
  appendStyleSheet();      
}
$("#contrast-btn a").click(function () {
    if ($.cookie('high_contrast') != 'true') {

        appendStyleSheet();      
        $.cookie('high_contrast', 'true'); // Set cookie to true
    }       
    else {
        // Remove high-contrast style
        $("#hc_stylesheet").remove();
        $.cookie('high_contrast', 'false');
    }
});
});

You can customize the cookie by setting options such as expiration date or domain-wide validity. For example, to make the cookie valid for a year:

$.cookie('high_contrast', 'false', {expires: 365});

If you want it to be valid across your entire domain, specify the path as '/':

$.cookie('high_contrast', 'false', {path: '/'});

Answer №2

To simplify your code, you can define the highContrast variable within the global context for future reference on the same page:

var highContrast = false;
$(document).ready(function(){
    // [...]
    highContrast = true;
    // [...]
});

However, this value will be reset on each page refresh. To address this, you can utilize cookies with the help of the jquery-cookie plugin:

$.cookie('highContrast', 'true', { path: '/' });

Retrieve and check the cookie value on page load:

if ($.cookie('highContrast') && $.cookie('highContrast') === "true") {};

By setting path = '/', the cookie will remain accessible across the entire domain.

With these adjustments, your code would look like this:

$(document).ready(function(){
    // Add the stylesheet when the page loads
    if ($.cookie('highContrast') === "true") {
        $('head').append('<link rel="stylesheet" href="css/high-contrast.css" type="text/css" id="hc_stylesheet"/>');
    }
    // Implement a click handler to toggle the stylesheet
    $("#contrast-btn a").click(function () {
        if (!(($.cookie('highContrast') === "true"))) {
            $('head').append('<link rel="stylesheet" href="css/high-contrast.css" type="text/css" id="hc_stylesheet"/>');
            $.cookie('highContrast','true',{path:'/'});
        }       
        else {
            // Remove the high-contrast style
            $("#hc_stylesheet").remove();
            $.cookie('highContrast','false',{path:'/'});
        }
    });
});

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

Utilize Bootstrap's form-inline feature to arrange fields side by side in one neat

I am looking to customize my sign-in form layout by displaying the fields in a row next to each other rather than under each other. header: Update: I have successfully implemented this code <header class="navbar navbar-fixed-top navbar-inverse"> & ...

Designating a class for the main block

Having an issue with a slider in uikit. When the slide changes, the visible elements also change their class to uk-active. I'm trying to select the central element from the active ones but css nth-child doesn't work. Any suggestions on how to do ...

What are the ramifications of using the 'new' keyword in JavaScript?

Currently, I am in the process of developing a plugin for jQuery, and I am encountering a JSLint error that redirects to JSLint: Problem at line 80 character 45: Do not use 'new' for side effects. (new jQuery.fasterTrim(this, options)); Despit ...

Trouble with AJAX BitMovin: unable to process GET request

I've been struggling to find a solution to my problem as I cannot pinpoint what exactly to search for. My current issue involves using AJAX for a PHP Get request, causing it to submit and navigate away from the page. The BitMovin library appears to b ...

enclose code within square brackets

I have a shortcode function that currently works with or without square brackets. However, I would like it to only work with square brackets. shortcode (Current) itemText num="1" title="This is a title" shortcode (Desired) [itemText n ...

I am attempting to properly arrange my navigation links and logo in alignment

I need help aligning the logo in the exact center while keeping the navigation links as they are. Here is how it currently looks: https://i.stack.imgur.com/qOgVJ.jpg My CSS: .logo { display: inline-block; text-align: center; } na ...

Guide on creating a stationary side navigation bar in HTML with Bootstrap 5 and CSS

I am developing a website with a fixed side navigation bar that stays in place when scrolling through the content section. I experimented with both the fix-position in Bootstrap 5 and CSS methods, but no matter how I set it up, the side bar remains transpa ...

Passing a JSON object to a different page using jQuery

I'm currently facing a challenge with sending JSON data (demographics) to a new page within the same directory when a user clicks on a marker that I've placed on a Google map on my website. I am using the jquery-ui-map plugin, and while the marke ...

Display a DIV element when a specific date is chosen using bootstrap-datepicker

Looking to incorporate the bootstrap-datepicker plugin using the provided markup... Is there a way to display a DIV element when selecting a specific date and then hide it again when another date is chosen? <head> <script src="https://cdnjs.cl ...

What is the best way to update the src of an input using an onclick event?

When I click the input, my background changes color as expected. However, the src of the input only changes on the second click. How can I make it change the source on the first click? Also, how can I change the src back to the original with a second cli ...

Tips for effectively utilizing the page-break property within CSS

I am faced with an issue on my HTML page where multiple angular material cards are being displayed: ... <mat-card class="mat-card-98"> <mat-card-header> <mat-card-title>THIS IS MY TITLE</mat-card-title> < ...

The hyperlinks in the navigation bar are leading me to incorrect destinations

I am currently developing an authentication app and facing an issue with the navbar links for register and login. They are not redirecting me to the correct destination. These links work perfectly on the landing index page, but not on any other page. site ...

SimpleLightBox refuses to function

Having trouble getting SimpleLightBox to work properly? It seems like when you click on an image, it opens as a regular image on a blank page. I've added the JS and CSS files correctly (I double-checked in the source code) and included the HTML and JS ...

Enhance your Coda experience with custom Jade and Stylus syntax highlighting!

Has anyone successfully tried using both Haml and Less? I attempted to use them since they are similar, but unfortunately had no luck. The Less one appeared in modes, while the Haml one didn't even show up. I also added the file type in the preferenc ...

Is there a method for capturing a single frame from a video and storing it in memory?

Trying to extract a frame and save it as output.jpg on the server side: Command: "ffmpeg -vframes 1 -y -ss "+time+" -i ./media/somemov.mp4 ./media/output.jpg" Subprocess.call(command, shell=True) On the client side, using: getImage(noOfFrame); //request ...

A useful Javascript function to wrap a string in <mark> tags within an HTML document

I have a paragraph that I can edit. I need to highlight certain words in this paragraph based on the JSON response I get from another page. Here's an example of the response: HTML: <p id="area" contenteditable> </p> <button class="bt ...

Determine the hexadecimal color value by combining two different colors along with a specified percentage/position

Can a color in the middle of a gradient be calculated? var initialColor = 'FF0000'; var finalColor = '00FF00'; // At 50% between the two colors, it would result in '808000' var middleColor = determineMiddleColor(initialColor ...

What could be causing this element to not float left in Firefox?

Can anyone help with aligning a checkbox to float left in Firefox? I can't seem to figure out what's causing the issue. Example that demonstrates the issue: http://jsfiddle.net/3zhrD/ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional ...

`Turn a photo into a circular shape by cropping it`

Even though I know that the solution involves using border-radius: 50%, it doesn't seem to be working for my situation. In my code using React/JSX notation, this is how the icon is displayed: <i style={{ borderRadius: '50%' }} className= ...

Experiment with altering the layout of certain navigation bars

I am currently attempting to customize the background color and text color for specific HTML components. Within my project, there are 3 navigation bars. I aim to establish a default color for all nav bars while also altering the specific color of one of t ...