7

I need to add a cookie to this script so when you click #full-width or #fixed-width it will remember your view on your next visit

<button id="full-width">GO FULL WIDTH</button>
<button id="fixed-width">GO FIXED WIDTH</button>

$(document).ready(function () {

    $("#full-width").click(function () {

        $('head').append('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');

    });

    $("#fixed-width").click(function () {

        $('link[rel=stylesheet][href="http://www.nitrografixx.com/2015/ladder/full-ladder.css"]').remove();

    });

});

I found this cookie that was already on my site for another script , but i don't have any idea on how to install it for the script above.

function setCookie(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=/; domain=.myfantasyleague.com";
}

function getCookie(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 deleteCookie(name) {
    createCookie(name, "", -1);
}
MShack
  • 642
  • 1
  • 14
  • 33
  • 2
    Dont swap the stylesheets. Just make two classes and and using jquey addClass and removeClass function and swap classes. It will work fine. CSS files have to be loaded on page load, changing them dynamicall will never work. That's why we don include them on the end of document. only works when included before the html content – Ila Jun 29 '15 at 04:22
  • They do work when you swap them actually, if you risk of visual glitches, that is :) – myTerminal Jun 29 '15 at 04:40
  • When the user selects a different layout, store that option in a cookie. For each page load, check if the cookie exists and also the value of that option, and insert the alternative stylesheet when a certain condition is met. – Terry Jun 29 '15 at 05:02

3 Answers3

4

I think cookies are a bit overkill for this and are not really needed. You can do this a nice way with localStorage instead if you don't have to use cookies for other various reasons not stated.

https://jsfiddle.net/4bqehjfc/3/

var fullWidth = function() {
        $('head').append('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');
    },
    fixedWidth = function() {
        $('link[rel=stylesheet][href="http://www.nitrografixx.com/2015/ladder/full-ladder.css"]').remove();
    };

$("#full-width").click(function () {
    localStorage.setItem('width', 'full-width');
    fullWidth();
});

$("#fixed-width").click(function () {
    localStorage.setItem('width', 'fixed-width');
    fixedWidth();
});

if (localStorage.getItem('width') == 'fixed-width') {
    fixedWidth();   
} else if (localStorage.getItem('width') == 'full-width') {
    fullWidth();
}

The important bit is: localStorage.setItem() and localStorage.getItem().

localStorage is well supported and offers a nice clean alternative to Cookies (for some purposes) but also has it's own limitations. See here.

One important thing to note is switching stylesheets like this you are going to flashes of unstyled content whilst the stylesheets are fetched which isn't very nice. You would want to use localstorage to append a CSS class and change the styles this way if you have the flexibility to do so.

Community
  • 1
  • 1
Matt Derrick
  • 5,674
  • 2
  • 36
  • 52
  • This is perfect , but i do have a issue. The server i'm loading this onto is odd. In that it has 2 ids for the server depending on which page you click on. Server url string www.thissite.com and football.thissite.com . I used your method and works great , but you have to set the view on both url strings for them to take. Any method that would cover the entire domain thissite.com ? – MShack Jul 01 '15 at 14:12
  • When I wrote the line 'it has it's own limitations' this was one I had in mind! `localStorage` across subdomains is an issue which I have experienced well. Hopefully this will get you started: https://github.com/ofirdagan/cross-domain-local-storage - You have to use an iFrame and such. – Matt Derrick Jul 01 '15 at 14:16
  • Also you masked your domain in the above comment by using `thissite.com` but in your cookie code snippet above it is visible. Just an FYI incase you want it obscured. – Matt Derrick Jul 01 '15 at 14:19
0

Considering this:

HTMLStyleElement.disabled

Is a Boolean value, with true if the stylesheet is disabled, and false if not.

(source) you can do the following:

<style id="first" disabled >@import url(/a.css);</style>
<style id="second" >@import url(/b.css);</style>

and code:

$("#first-on").click(function () {
  $("#second")[0].disabled = true;
  $("#first")[0].disabled = false;
});
c-smile
  • 26,734
  • 7
  • 59
  • 86
  • I need to add a cookie to the existing script , i don't need another way to perform the switch. Thanks – MShack Jun 30 '15 at 21:19
  • What exactly is "to add a cookie to the existing script"? – c-smile Jun 30 '15 at 21:47
  • I need to add a cookie to this script so when you click #full-width or #fixed-width it will remember your view on your next visit – MShack Jun 30 '15 at 22:08
0

In case you run into some of the Known Issues with localStorage, this sample below works with the cookie functions you provided.

Note that we'll avoid using jQuery for the initial portion of the code here in an effort to reduce/remove the initial flash that might be experienced if someone had the layout cookie set to full width.

I also upgraded your button a little :)

<!doctype html>
<html>
<head>
    <title>Cookiesheet</title>

    <script>
    var layoutcookiename = 'layout_cookie'; //just in case you want to rename the cookie for your layout
    var layoutcookiedays = 30; //how many days do you want the cookie to last for
    var mycookiedomain = '.nitrografixx.com';  //add a period in front of your domain name here to include it for all subdomains

    var layoutcookie = getCookie(layoutcookiename); //Get the stored cookie if any

    //Assuming the default layout will be fixed width
    var currentlayout = (layoutcookie === null || layoutcookie === 'fixed') ? 'fixed' : 'full';
    //If default is to be full width, uncomment and use this if statement instead of the preceding line
    //var currentlayout = (layoutcookie === null || layoutcookie === 'full') ? 'full' : 'fixed';

    if (currentlayout === 'full') {
        document.write('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');
    }

    //We only need the function to get cookies up here
    function getCookie(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;
    }
    </script>
</head>
<body>

<!-- Dynamic button text for initial load -->
<button id="layout-switch"><script>if (currentlayout === 'fixed') { document.write('GO FULL WIDTH'); } else { document.write('GO FIXED WIDTH'); }</script></button>

<!-- The rest of the javascript that can occur on document ready -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $('#layout-switch').click(function () {
        if (currentlayout === 'fixed') {
            $('head').append('<link rel="stylesheet" href="http://www.nitrografixx.com/2015/ladder/full-ladder.css" type="text/css" />');
            $(this).html('GO FIXED WIDTH');
            currentlayout = 'full';
        } else {
            $('link[rel=stylesheet][href="http://www.nitrografixx.com/2015/ladder/full-ladder.css"]').remove();
            $(this).html('GO FULL WIDTH');
            currentlayout = 'fixed';
        }

        setCookie(layoutcookiename, currentlayout, layoutcookiedays);
    });
});

function setCookie(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=/; domain=" + mycookiedomain;
}

function deleteCookie(name) {
    createCookie(name, "", -1);
}
</script>
</body>
webworker01
  • 910
  • 9
  • 6