WordPress Code Snippets

A fresh mix of code snippets and tutorials

jQuery switch styles

86

Switching CSS styles on click (or other event) is easily accomplished with jQuery. Here are two examples showing how to use jQuery to switch styles.

First method (link element)

This method adds a live <link> element to the <head> section, enabling you to include, import, and customize alternate styles as needed.

// toggle stylesheet jQuery plugin
function wpmix_toggle_stylesheet(){
	$('body').append('<div class="button" id="wpmix-toggle-css">Alt styles</div>');
	$("#wpmix-toggle-css").toggle(function(){
		$(this).text('Alt styles');
		$('head').append('<link rel="stylesheet" media="all" title="alt_css" href="lib/alt.css">');
	},function(){
		$(this).text('Remove alt styles');
		$("[title=alt_css]").remove();
	}).css({
		position:'fixed', top:'0', right:'24px', zIndex:999, padding:'0.75em', cursor:'pointer'
	});
}
$(document).ready(function(){
	wpmix_toggle_stylesheet();
});

Better method (class attribute)

Here’s another way to switch CSS styles by adding/removing a class attribute to/from the <html> element.

// jQuery switch styles
$(document).ready(function() {
	$('body').append('<div class="button" id="wpmix-toggle-css">Alt styles</div>');
	$('#wpmix-toggle-css').toggle(function(){
		$(this).text('Alt styles');
		$('html').addClass('alt-css');
	},function(){
		$(this).text('Remove alt styles');
		$('html').removeClass('alt-css');
	}).css({
		position:'fixed', top:'0', right:'24px', zIndex:999, padding:'0.75em', cursor:'pointer'
	}).hover(function(){
		$(this).css('opacity',0.9);
	},function(){
		$(this).css('opacity',0.6);
	});
});

Then in your CSS, apply the alternate styles as needed by targeting the html.alt-css class, which is dynamically added when the “Alt styles” button is clicked.

Bonus tip

To load a specific alternate stylesheet for some page(s) and a different custom stylesheet for other pages, use the first method (above) and add the following snippet (i.e., replace line 6 with these lines):

var url = $(location).attr('href');
if(url = 'http://example.com/') {
	$('head').append('<link rel="stylesheet" href="lib/alt.css" title="alt-css" media="all">');
} else {
	$('head').append('<link rel="stylesheet" href="lib/custom.css" title="alt-css" media="all">');
}

Remember to replace the example.com with the URL(s) of your choice.


Show Support

Like our new Facebook Page to show support!