Switch CSS library simplified

Now let’s take a look at how to change stylesheet, and keep them the style there after reload using cookies.

Quick overview

1. Include the latest version of jquery and include jquery.cookie.js found here.
2. Add html links

<link href="css/styles1.css" rel="stylesheet" title="custom css" id="custom-css">
<a href="#" id="css1">1</a><a href="#" id="css2">2</a><a href="#" id="css3">3</a><a href="#" id="css4">4</a>

2. Add jquery script to make the button active

$(document).ready(function(){
	$('#css1').click(function(){
	    $('#custom-css').attr('href', 'css/styles1.css');
	});
	
	$('#css2').click(function(){
	    $('#custom-css').attr('href', 'css/styles2.css');
	});
	
	$('#css3').click(function(){
	    $('#custom-css').attr('href', 'css/styles3.css');
	});
	
	$('#css4').click(function(){
	    $('#custom-css').attr('href', 'css/styles4.css');
	});
});

3. And that’s it! Once you click on the links, it will tell your styles to change!

4. Now for the cookie,

<link href="#" rel="stylesheet" title="custom css" id="custom-css">

and use this script

$(document).ready(function(){

	$('#css1').click(function(){
	    $('#custom-css').attr('href', 'css/styles1.css');
	    $.cookie('stylesheet', 'css/styles1.css');
	});
	
	$('#css2').click(function(){
	    $('#custom-css').attr('href', 'css/styles2.css');
	    $.cookie('stylesheet', 'css/styles2.css');
	});
	
	$('#css3').click(function(){
	    $('#custom-css').attr('href', 'css/styles3.css');
	    $.cookie('stylesheet', 'css/styles3.css');
	});
	
	$('#css4').click(function(){
	    $('#custom-css').attr('href', 'css/styles4.css');
	    $.cookie('stylesheet', 'css/styles4.css');
	});
	
	var cookieValue = $.cookie('stylesheet');
	if (cookieValue == null ){
		$('#custom-css').attr('href', 'css/styles1.css');
	};
	$('#custom-css').attr('href', cookieValue );
});

Leave a comment

Your email address will not be published. Required fields are marked *

four + 17 =