JavaScript - - By Sam Deering

jQuery Change CSS File Dynamically

How to change a css file dynamically using nothing but good old fashion jQuery! (it’s kinda like a jQuery stylesheet switcher!)

The jQuery

$(document).ready(function() {
	$("#nav li a").click(function() {
		$("link").attr("href",$(this).attr('rel'));
		return false;
	});
});

OR (a more complex version to swop the css files dynamically)

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

OR (a version which reduces the flicker which occurs when ths page refreshes with the new css syles after the css is swopped using the relative attribute of the link in the html code).

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

The HTML

The html is simple with the css and jQuery files loaded as normal in the header of the html.

Test it out! Here is a couple of links to try it for yourself.

Source
Demo

Sponsors