3

I want to change the used CSS File (<link href="..." />) dynamically using only javascript and to save changes in cookies.

This is a jQuery version that does what I want (ref), but how can I do this in javascript?

if($.cookie("css")) {
    $("link").attr("href",$.cookie("css"));
}
$(document).ready(function() {
    $("#nav li a").click(function() {
        $("link").attr("href",$(this).attr('rel'));
        $.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
        return false;
    });
});

Thank you in advance.

AndraD
  • 2,830
  • 6
  • 38
  • 48
Vahid
  • 3,384
  • 2
  • 35
  • 69

2 Answers2

5

maybe this could help you..

(function() {
    var e = document.createElement('link'); 
    e.href = document.location.protocol + '//example.com/file.css';
    e.type = 'text/css';
    e.rel = 'stylesheet';
    e.media = 'screen';
    document.getElementsByTagName('head')[0].appendChild(e);      
}());

Edit, full JavaScript without jQuery

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);
}

document.addEventListener('DOMContentLoaded',function(){

    if(readCookie('css')){
        var e = document.getElementById('test-css'); // <link href="..." id="test-css"/>
        e.href = readCookie('css'); 
    }

    var element = document.getElementById('change-css'); // <a herf="#" id="change-css" rel="file.css">Click Here</a>
    element.addEventListener('click', function (event) { 
        var e = document.getElementById('test-css');
        e.href = this.rel;
        if(readCookie('css')){  
            eraseCookie('css');     
        }
        createCookie('css',this.rel,365); 
        event.preventDefault(); 
    }, false);
})
  • I don't want to Adding a CSS File but change it. So can you edit your post? Thanks. – Vahid Sep 01 '12 at 16:31
  • The last part is combining of both jquery and javascript? Maybe another edit required but I'll check the other parts. Thanks. – Vahid Sep 01 '12 at 17:08
2

Read: http://www.quirksmode.org/js/cookies.html

And: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

First, lets make an example html layout.

<html> <!--#include javascript.js styles.css-->
    <body>
        <span>sometext</span>
        <p>somemoretext</p>
    </body>
</html>

Next, lets make an example css layout.

span {
    color: red;
}

p {
    color: blue;
}

body {
    background: black;
}

Now is the javascript. Before we do anything, cookies cannot store css information. We will use cookies names to determine the type of style to load. The quirksmode resource above lets us easily use cookies.

if(readCookie("newStyle")) {
    // do something
} else {
    // do something else
}

In this case, we want to change the styles. We can use two methods: document.element.style.property or appendChild with the href of another CSS sheet. In this example, we use document.element.style.property.

if(readCookie("newStyle")) {
    eraseCookie("newStyle")
    document.getElementsByTagName("span")[0].style.color = "purple"
    document.getElementsByTagName("p")[0].style.color = "pink"
} else {
    createCookie("newStyle",0000,60)
}

Live Example: http://jsfiddle.net/5HGsH/3/

Refresh the page multiple times to see different colored words.

  • +1 for good information here but not related to my question. I want to change **CSS File** (href location) not inner style of elements. Thanks. – Vahid Sep 01 '12 at 17:04
  • You cannot change a CSS file on the server/client's side using javascript. You either have to load another CSS file or edit the existing CSS in the DOM. If you need server-side scripting look at PHP. –  Sep 01 '12 at 17:13
  • 1
    jQuery version in my post exactly says what I wanted. I want to change the href location of an external css file in my html base on click of an element. – Vahid Sep 01 '12 at 17:17