Changing the Background Color of a Page using jQuery

I wanted to develop something that would allow the user to change the background of my site but without having to load a separate stylesheet so thats where jQuery comes in. As you will see below, jQuery allows you to manipulate html elements through the use of classes defined in CSS and it’s easier than you think.

jqueryBg

Take a peak of the working demo.

The HTML and CSS

Before we get underway, we need to include the jQuery library.

<script type="text/javascript" src="js/jquery-1.2.6.pack.js"></script>

Then we create a simple unordered list of links, each with a unique class.

<ul>
	<li class="one"><a href="#"></a></li>
        <li class="two"><a href="#"></a></li>
        <li class="three"><a href="#"></a></li>
</ul>

Next we create three classes in the CSS. These are the styles used for the background which will be applied via jQuery.

.bg1 { background: url(images/red.jpg) repeat-x; background-color: #6c0000; }
.bg2 { background: url(images/orange.jpg) repeat-x; background-color: #5A2A00; }
.bg3 { background: url(images/blue.jpg) repeat-x; background-color: #00345B; }

The jQuery Magic

What you see below is basically jQuery functions that add or remove classes to the body element based on what list item the user clicks on. As you can anyone who has experience of CSS will be immediately familiar with the processes below. The classes setup in CSS are being applied to the body tag of the site, changing the background image and colour.

$(document).ready(function(){ 

        $("li.one").click( function(){ $
		("body").removeClass('bg2 , bg3').addClass("bg1");
	});

	$("li.two").click( function(){ $
		("body").removeClass("bg1 , bg3").addClass("bg2");
	});

	$("li.three").click( function(){ $
		("body").removeClass("bg1 , bg2").addClass("bg3");
	}); 

});

As you can see it’s fairly easy to understand jQuery at this basic level. To perform the same task without a javascript framework would require weeks and weeks of learning. Make sure you find out more about jQuery and have fun!

by @tkenny

You should follow me on Twitter here

Subscribe to Inspect Element by email to get updates on new articles, tutorials and WordPress themes: