Skip to main content

jQuery Change CSS File Dynamically

By Sam Deering

JavaScript

Share:

😳 Ever felt a little embarassed sharing your JavaScript? Let's fix it.

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

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

💁‍♀️ Fun Fact: Python was ranked #2 on a recent highest paid coders list. *


🤓 Ok. When did a code editor from Microsoft become kinda cool!?