In this tutorial we will be creating a expand/collapse banner which will help you learn the basics of jQuery.

Assumed Knowledge

  • Basic HTML structure
  • Basic CSS

What is jQuery?

" jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript." – Source www.jquery.com

What are we creating?

We will be creating a expand/collapse banner which will help you learn the basics of jQuery.

This banner could be used to display advertisements on your site where you have limited space.

The techniques you learn in this tutorial will allow you to create and control other animated elements for your website

View DEMO | Source Files

The Banner

As this is not a tutorial about Photoshop I will not explain the creation of the banner, just how your banner should be formatted (you can use my included banner to follow along or create your own)

Our banner has two distinct states, one is when the banner is collapsed the other is when the banner is expanded.

To ensure that our banner is already loaded when switching between states we will create our banner as one image and change the background position using jQuery.

The following image shows my banner with the "collapsed" state (in green) and "expanded" state (in red) and the respective dimensions. (NOTE: You can make your banner any dimensions you wish).

Our Banner Format

Our Banner Format

As you can see our "collapsed" banner is 915px by 40px and our "expanded" banner is 915px by 240px. Make note of the dimensions of our banner as we will be using these in our jQuery.

Getting Setup


Now that we have our banner ready we can work on the HTML, CSS and JavaScript (jQuery) that will support it.

Start by creating a new folder called "jquery_tutorial" and within it add a folder called "images", "js" and "css" your folders should look like this:

Now you will need to:

  • copy the file called "jquery-1.6.4.min.js" from the source files and add it to your "js" folder.
  • add your banner image to the "images" folder

If you are using my banner as an example then copy "banner.jpg" from the source files and add it to your "images" folder.

Index.html


Header Section

Now in the "jquery_tutorial" directory, create a new file called "index.html"

This is our basic HTML file to which we will be adding our JavaScript and other code.

Add the following lines in the head section of your html document directly below the title:

1
2
3
4
5
6
<!-- Custom fonts -->
    <link href="http://fonts.googleapis.com/css?family=Droid+Sans:regular,bold" rel="stylesheet">
    <!-- Include CSS -->
    <link rel="stylesheet" href="css/styles.css">
    <!-- Include Jquery -->
    <script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>

This code allows us to:

  • access the font “Droid Sans” from Google
  • reference our CSS stylesheet “styles.css” which we will create shortly
  • reference our "jquery-1.6.4.min.js" file which is the latest copy of the jQuery code library. ( Version 1.6.4 was the latest version at the time of writing, visit www.jquery.com to check for a newer version of jQuery)

Body

Now to the body section of index.html add the following code:

1
2
3
4
5
6
7
8
9
10
<div id="container">
   
      <div id="ad_text">Advertisement</div>
       
      <div id="toggle">
                    <a id="open" class="open" href="#">Expand</a>
                    <a id="close" class="close" href="#">Collapse</a>          
      </div>
      <a href="http://www.designandcode.com.au" target="_blank"><div id="panel"></div></a>
</div>
  • Our code is surrounded by a DIV named “container” that will hold all our elements within it and centre them on the page.
  • We have an optional DIV called “ad_text” which simply has the word “advertisement” in it which will sit on the top left of our banner.
  • We have a DIV named “toggle” which will hold our “Expand”/”Collapse” buttons which we will use jQuery to toggle between.
  • Finally we have a DIV called “panel” which is wrapped in an <a href> link tag which allows us to link our banner to a url/file. If you do not wish your banner to link to anything simply replace this line with "<div id="panel></div>" only.

styles.css


Now create a new stylesheet named “styles.css” and place it in the “css” folder. Add the following code to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/***************** General styles *****************/
    body {
    color: #666;
    font-size: 12px;
    font-family: "Droid Sans", Arial, sans-serif;
   
    }
    a { text-decoration: none; }

    a:hover { text-decoration: underline; }
   
    #panel {
    float: right;
    overflow: hidden;
    background-image: url(../images/banner.jpg);
    }

    #toggle {
    float: right;
    margin-right: 5px;
    margin-bottom: 3px;
    }
   
    #ad_text {
    float: left;
    margin-bottom: 3px;
    margin-left: 5px;
    }
    #container {
    margin-right: auto;
    margin-left: auto;
    }
  • In the #panel DIV change “banner.jpg” to the name of your banner, if you are using my example banner or named your own banner “banner.jpg” then you don’t need to change anything.
  • Note that we haven’t set any height/width properties for our #panel DIV, this is because we will set these properties using jQuery in the next section.

jQuery


Now we are ready to write our JavaScript code which will reference the jQuery library.

Open up “index.html” and in the head section paste the following code below the line where we referenced “jquery-1.6.4.min.js”:

1
2
3
4
5
<script type="text/javascript">
        $(document).ready(function(){
            //Code Goes Here
        });
</script>

This piece of code calls a jQuery function that tells the browser to run our code when our document is ready.

Set some variables

The “//Code goes here” is a comment that won’t be displayed by the browser, replace “//Code goes here” with the following:

1
2
3
4
5
6
7
8
9
10
11
//Set the banner width in pixels
        var banner_width = 915;
       
        //Set the height of the large banner in pixels
        var large_banner_height = 240;
       
        //Set the height of the small banner in pixels
        var small_banner_height = 40;
       
        //Set whether you want the banner to start expanded or collapsed. set to "0" for expanded or "1" for collapsed (Defaults to collapsed "1" )
        var initial = 1;
  • This code allows us to set some variables before we run our script.
  • By setting the values of our banner here, we are able to customise the script in the future much easier.
  • Replace the values in the code with the values of your “collasped” and “expanded” banner.
  • The final line determines if you want your banner to be “expanded” or “collapsed” when the page loads. I have set mine to “1” which means the banner starts in a “collasped” state.

Set some CSS properties

Now add the following code below our previous code:

1
2
3
4
5
// Set our container width to the width of our banner
        $("div#container").css({width:banner_width+"px"});
       
// Set our panel width to the width of our banner
        $("div#panel").css({width:banner_width+"px"});
  • This code sets the width property of our #container and #panel DIVs the the value of “banner_width” which is the variable we previously set
  • We can set CSS properies for our HTML elements using jQuery in the following format: $(“HTML ELEMENT”).css({PROPERTY: VALUE});
  • $(“#container”) and $(“div#container”) are equivilant, I chose the later to make it clear we are talking about a DIV.
  • If we weren’t inserting a variable into our code it would look like:
  •     $("div#container").css({width:"915px"});
        $("div#panel").css({width:"915px"});
        

Initialise our banner state

Now add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Set the advertisement to "expanded" or "collapsed" based on user settings
        if (initial == 0) {
                // The banner will start expanded
                $("div#panel").css({height:large_banner_height+"px"});
                //Move the background up the hieght of our small banner to display full advertisement
                $("div#panel").css("background-position", "0px -"+small_banner_height+"px");
                //Set "expand" to be hidden
                $("#toggle a#open").css("display", "none");
           
            }else if (initial == 1){
               
                // The banner will start collapsed 
                $("div#panel").css({height:small_banner_height+"px"});
                //Reset the background
                $("div#panel").css("background-position", "0px 0px");
                //Set "expand" to be hidden
                $("#toggle a#close").css("display", "none");
        }
  • This script will run one block of code based on the “initial var” we set earlier. If initial is “0” (expanded) we run the first block, if initial is “1” (collapsed) we run the second block.
  • Our first line sets the height of our #panel DIV to “large_banner_height” or “small_banner_height”
  • Our second line sets the CSS property “background-position” for our #panel DIV. If the banner starts expanded we set our background position to move 0px on the x axis and negative 40px on the y axix.
    If our banner starts collapsed our background position is set to a default of 0px on the x axis and 0px on the y axis.
  • The final line sets our anchor id (<a id="value"></a> tags) “open” or “close” within the #toggle DIV to be hidden (“display”, “none”)

Let’s take a closer look at the #toggle DIV in the body of our HTML and the last line of our jQuery code block.

1
2
3
4
<div id="toggle">
                    <a id="open" class="open" href="#">Expand</a>
                    <a id="close" class="close" href="#">Collapse</a>          
      </div>
1
2
//Set "expand" to be hidden  
$("#toggle a#open").css("display", "none");
  • We can select elements within DIVs by using the id of inner elements. In our example, $(“#toggle a#open”) refers to the anchor id “open” inside the DIV id “toggle”
  • By setting the CSS display property to “none” we have the element hidden

Expand the panel
Add the following code to our JavaScript:

1
2
3
4
5
6
7
 // Expand Panel
        $("#open").click(function(){
            // Animate #panel to its full width and height
            $("div#panel").animate({height: large_banner_height+'px'});
            //Move the background up the height of our small banner to display full advertisement
            $("div#panel").css("background-position", "0px -"+small_banner_height+"px");    
        });
  • This code is for when someone clicks on the HTML element with id=”open” which is our text “expand”
  • We use the jQuery function animate() which will animate our #panel DIV from it’s current state to the values we provide
  • We give animate() the properties of height: large_banner_height+’px’ which expands our banner to it’s full height. As our banner only expands vertically, we only need to
    provide a property for height. If we wanted it to expand horizontally and vertically we could give it a height AND width property.
  • To add multiple properties simply seperate them with a comma. For example animate({height: ‘240px’, width: ‘1000px’});

Collapse the panel

Add the following code to your javascript:

1
2
3
4
5
6
7
8
9
// Collapse Panel
        $("#close").click(function(){
            //Animate #panel to the small size advertisement
            $("div#panel").animate({width: banner_width+'.px',height: small_banner_height+'px'},function() {  
                //After the animation is complete, reset the background to it's original position.
                $("div#panel").css("background-position", "0px 0px");
            });
           
        });
  • This code is very similar to our “open the panel” script except for one key difference.
  • You can see that within our animate() function we have added a comma after the “}” and added another function
  •     ,function() {    
                    //After the animation is complete, reset the background to it's original position.  
                    $("div#panel").css("background-position", "0px 0px");  
                });  
        
  • This is a function that will run once our animation is complete.
  • The function resets the background position of our #panel DIV once the banner has collasped which resets it to show our “collapsed” banner.

Toggle

Add the following code to your JavaScript:

1
2
3
4
// Switch buttons from "Expand" to "Collapse" on click
        $("#toggle a").click(function () {
            $("#toggle a").toggle();
        });
  • This uses the toggle() function in jQuery which switches between the states of an element
  • In our case this will switch the text within the #toggle DIV from “expand” to “collapse”

Complete

Congratulations you have now written all the code you need for our expand/collapse banner to work.

The entire JavaScript code together is written below, please check through it and make sure you have added all the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<script type="text/javascript">
        $(document).ready(function(){
       
        //Set the banner width in pixels
        var banner_width = 915;
       
        //Set the height of the large banner in pixels
        var large_banner_height = 240;
       
        //Set the height of the small banner in pixels
        var small_banner_height = 40;
       
        //Set whether you want the banner to start expanded or collapsed. set to "0" for expanded or "1" for collapsed (Defaults to collapsed "1" )
        var initial = 1;
       
        // Set our container width to the width of our banner
        $("div#container").css({width:banner_width+"px"});
       
        // Set our panel width to the width of our banner
        $("div#panel").css({width:banner_width+"px"});
       
       
        // Set the advertisement to "expanded" or "collapsed" based on user settings
        if (initial == 0) {
                // The banner will start expanded
                $("div#panel").css({height:large_banner_height+"px"});
                //Move the background up 35px to display full advertisement
                $("div#panel").css("background-position", "0px -"+small_banner_height+"px");
                //Set "expand" to be hidden
                $("#toggle a#open").css("display", "none");
           
            }else if (initial == 1){
               
                // The banner will start collapsed 
                $("div#panel").css({height:small_banner_height+"px"});
                //Reset the background
                $("div#panel").css("background-position", "0px 0px");
                //Set "expand" to be hidden
                $("#toggle a#close").css("display", "none");
        }
           
        // Expand Panel
        $("#open").click(function(){
            // Animate #panel to its full width and height
            $("div#panel").animate({height: large_banner_height+'px'});
            //Move the background up 35px to display full advertisement
            $("div#panel").css("background-position", "0px -"+small_banner_height+"px");    
        });
   
        // Collapse Panel
        $("#close").click(function(){
            //Animate #panel to the small size advertisement
            $("div#panel").animate({width: banner_width+'.px',height: small_banner_height+'px'},function() {  
                //After the animation is complete, reset the background to it's original position.
                $("div#panel").css("background-position", "0px 0px");
            });
           
        });
       
           
        // Switch buttons from "Expand" to "Collapse" on click
        $("#toggle a").click(function () {
            $("#toggle a").toggle();
        });
       
        });
        </script>