In this lesson, let’s write a small script that allows users to choose their site background of your options. During the writing of the script we are using jQuery and jQuery Cookie plugin — it will help us to maintaining the user’s option. Thus, even after reloading the page or close the browser, the background will be the same as the user has selected.

Allow user to change page background on click

1. connect the scripts

First of all connect the jQuery library, if you have not yet connected, and the jQuery cookie plugin.

2. the HTML markup.
Choose your background:

In the block with the id panel-background we can have multiple blocks to be as buttons. Each has its own background image, we will assign classes. Also, these blocks have id, which must be the same as those of their class (you’ll understand why).

.button {
  width: 40px;
  height: 40px;
  border: 1px solid #ddd;
  float: left;
  margin: 7px 3px;
  cursor: pointer;
.button:hover {
  box-shadow: 0 0 3px rgba(0,0,0,0.5);
  border: 1px solid #fff;
.bg1 {background: #fff url("images/bg1.png");}
.bg2 {background: #fff url("images/bg2.png");}
.bg3 {background: #fff url("images/bg3.png");}
.bg4 {background: #fff url("images/bg4.png");}
.bg5 {background: #fff url("images/bg5.png");}
.bg6 {background: #fff url("images/bg6.png");}
.bg7 {background: #fff url("images/bg7.png");}

For each class, call its background image and leveled blocks in a line. Just added the hover styles and for the active block. This script allow user to change page background on mouse click.

$ (document) .ready (function () {

if ($. cookie (' body-bg ')) {  //if the Cook has already

var bgBody = $ cookie (' body-bg ');  //get the value of a cookie

$ (' the body ') addClass (bgBody);  //Add the class body
$ (' # ' + bgBody): addClass (' active ');  //Select the active button and give it a class of active


$ (' button ') click (function () {  //actions when clicking on a button (block div)

var bgBody = $ (' the body '). attr (' class ')  //get the current class and its variable prisvaevaem bgBody
bgId = $ (this). attr (' id ');   //get the value of the id, the button click

$ (' the body ') removeClass (bgBody): addClass (bgId); //remove the current class at body and add the chosen

$ (' button '). removeClass (' active ');  //remove all buttons active class
$ (this). addClass (' active ');  //the current buttons give active class

$ cookie (' body-bg ', bgId, {expires: 365});  //Add the Cook for a year



As you can see, the script is fairly small and simple. When you click on one of the blocks, the value of its id is written to the Cookie, and the body tag is given a class (same as the id block which is clicked) and the most active class is added to the block. In the beginning there is a test for the existence of a cookie, and if it already is, then just add the necessary classes, body and block the Panel.