Tuesday 14 October 2014

Website theme change using JQuery



For sites which dealing with multiple brands/organizations within it, we can style the site with different themes according to each brand/organization.
 For example, Volkswagen is an automobile group which makes cars in different brands like Audi, Skoda, Lamborghini etc.
In the Volkswagen site we can change the site theme for Audi/Skoda/Lamborghini using a simple click using JavaScript.
As we are using JavaScript we can avoid page reload, which will be fast and user friendly.
For making this we need different css files for each themes.
In our example above, let us assume the css file of Audi is audi.css
And on the theme change button of Audi, call the function … onClick=”SwitchStyle(audi);”

The Theme switch script is given below,
//THEME SWITCH
var styleCookieName = "SelectedBrand";
var styleCookieDuration = 1;
$(document).ready(function () {
    SetStyleFromCookie();  // set theme selected on page load
});

//SWITCH THEME STYLE ACCORDING TO BRAND
function SwitchStyle(cssTitle) {
    $("#theme").attr("href", "css/" + cssTitle + ".css");
    SetCookie(styleCookieName, cssTitle, styleCookieDuration);
    return false;
}

//REMEMBER CURRENT THEME UNTIL LOGOUT
function SetStyleFromCookie() {
    var cssTitle = GetCookie(styleCookieName);
    var keys = cssTitle.split(',');
    var cssName = keys[0];
    if (cssName) {
        if (cssName.length) {
            SwitchStyle(cssName);
        }
    }
}

//GET CURRENT THEME FROM COOKIE
function GetCookie(cookieName) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == cookieName) {
            return unescape(y);
        }
    }
}

//SET SELECTED THEME TO COOKIE
function SetCookie(cookieName, cookieValue, styleCookieDuration) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + styleCookieDuration);
    var c_value = escape(cookieValue) + ((styleCookieDuration == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = cookieName + "=" + c_value;
}

for changing the theme we need to give id="theme" for the default theme link in masterpage.
<link id="theme" href="css/default.css" rel="stylesheet" type="text/css" />
If we want to remember the theme we last selected we can give duration for the cookie. Or else just clear the “SelectedBrand” cookie in logout function.

No comments:

Post a Comment