jQuery for Complete Beginners: Part 3

Posted in Coding, Tutorials • Posted on 15 Comments

Welcome to the third post in this series, taking you from jQuery novice to jQuery expert. The past two weeks have essentially just listed functions that you will need to know. Today we are going to put the skills we’ve learned into practice (as well as meeting new things) and create a basic accordion.

An accordion is a very good way of showing lots of content in a small area. You might have five headers, each with a paragraph below it. Showing all that at once is going to go down for a long way. With the accordion, only one paragraph is shown at a time, and users can click on the headers to view the content they wish. First we will build a simple one and then we will animate it. You’ll see just how many built-in functions jQuery includes that makes our lives much easier. You can see the online demo here.

Firstly I set up the accordion itself:

<h3>Item 1
    <p>Item 1 content</p>
    <h3>Item 2
    <p>Item 2 content</p>
    <h3>Item 3
    <p>Item 3 content</p>
    <h3>Item 4</h3>
    <p>Item 4 content</p>

And then just some very basic CSS to make it look a bit clearer:

 p,h3 {margin: 0; padding: 0;}
        p {height: 150px; width: 200px; border: 1px solid black;}
        h3 {height: 50px; width: 200px; background-color: blue; color: white; border: 1px solid black;}

This leaves us with something similar to this. I’ve only taken a picture of the first two items to save space, and besides, the next two are identical.

Now we can get onto the JavaScript. Include jQuery from the google CDN, add your script tags to the bottom of your page and away we go:

var headings = $('h3'),
            paras = $('p');

All I am doing here is selecting all the heading 3 elements and all the paragraphs, and saving them to two arrays. Note the syntax, I could have done this:

var headings = $('h3');
var paras = $('p');

However I find it quicker to just put a comma between them and emit one of the ‘var’s. It’s also more commonly done that way.

Once we’ve done that we now need to hide all but the first paragraph. This is done like so, using a function eq():

paras.hide().eq(0).show();

First I hide all the paragraphs and then use eq(0) to select the ‘0th’ element of the ‘paras’ array. In JavaScript (and most languages) arrays start from 0, so 0 will select the first element. Using eq(1) would select the second element. I then use jQuery’s show() function show the first one. This leave us with something like this:

And now we can write the code for hiding and showing. Firstly, we need to add a click event to our headers:

 headings.click(function() {

 });

And we can write the code to go in it:

 var cur = $(this); //save the element that has been clicked for easy referal
 cur.siblings('p').hide(); //hide all the paragraphs
 cur.next('p').show(); //get the next paragraph after the clicked header and show it

Lets go through this line by line:

var cur = $(this);

Here we take the value of ‘this’ and wrap it in the jQuery object before saving it to a variable ‘cur’. ‘this’ refers to the current element being interacted with. In this case, it’s the heading element that has been clicked.

cur.siblings('p').hide();

The jQuery siblings() function finds all elements on the same level as the current element. Here we find all the siblings of the current element that are paragraphs and hide them. So now we know that there are no paragraphs being shown.

cur.next('p').show();

Finally we use jQuery’s next() function. This finds the next element from the one we have selected. In this case it finds the next paragraph and shows it.

And we’re done! If you try that in your browser, it works fine. However, seeing as jQuery gives us loads of animation functions, lets put a couple of those to use.

The two functions we will use are slideUp() and slideDown(). These do exactly what you would imagine, they animate an element sliding up until it’s gone, and then sliding it back down. In our click function that we wrote:

 headings.click(function() {
            var cur = $(this); //save the element that has been clicked for easy referal
            cur.siblings('p').hide(); //hide all the paragraphs
            cur.next('p').show(); //get the next paragraph after the clicked header and show it
        })

Replace the hide() function with slideUp() and the show() function with slideDown():

 headings.click(function() {
            var cur = $(this); //save the element that has been clicked for easy referal
            cur.siblings('p').slideUp(); //hide all the paragraphs
            cur.next('p').slideDown(); //get the next paragraph after the clicked header and show it
        })

And try now. Is it not beautiful?

That just about sums it up for this week. We’ve taken things discussed in the previous two weeks and put them together. We’ve also met another couple of functions to add to your jQuery repertoire.

4 Written ArticlesWebsite

Jack Franklin is a 17 year old budding web designer & developer living in Cornwall, England who enjoys messing with HTML, CSS, PHP & Javascript. Away from the desk, Jack enjoys badminton, football & snooker.

15 Comments Best Comments First
  • sunny

    Saturday, September 17th, 2011 12:25

    11

    Hi,

    how can I stop the already selected heading to again start the process of slideup and slidedown as
    I tried this

    headings.click(function() {
    var cur = $(this); //save the element that has been clicked for easy referal
    if (prevcur != cur) {
    cur.siblings(‘p’).slideUp(); //hide all the paragraphs
    cur.next(‘p’).slideDown(); //get the next paragraph after the clicked header and show it
    }
    var prevcur=cur;

    })

    but it didnt worked.

    +2
  • Nikola Dadić

    Thursday, April 22nd, 2010 19:21

    6

    i think you forget to close some tags in first code

    0
  • Web Risorsa

    Saturday, April 24th, 2010 11:16

    7

    Nice explanation… Looking for more of the same…

    0
  • obozdag

    Thursday, April 22nd, 2010 07:26

    5

    Easy to understand, useful, short article. Thanks.

    0
  • Negoita Cosmin

    Wednesday, April 21st, 2010 21:53

    4

    Nice article. It’s really simple! Thank you!

    0
  • Cook

    Wednesday, April 21st, 2010 17:45

    2

    a very well written article….

    0
  • Aisha

    Wednesday, April 21st, 2010 18:19

    3

    Beautiful Site, I really like it.

    0
  • NK

    Sunday, April 25th, 2010 01:08

    8

    thanks for sharing nice jquery thoughts….

    0
  • Keiron Lowe

    Wednesday, April 21st, 2010 16:57

    1

    Fantastic, been waiting a while for the next bit of this series. Your really good at describing what the code does and such. Cheers

    0
  • gopi

    Friday, December 9th, 2011 13:17

    14

    hi,i want a code to validate a text box using jquery,,anyone pls send me the code …

    0
  • Anna

    Wednesday, April 11th, 2012 06:12

    15

    Thanks a lot. It is cool. Explanation is dead easy compared to other sites

    0
  • niaz

    Friday, December 2nd, 2011 18:13

    13

    this is very nice site, i have learned a lot about mobile website, wordpress plug in jquery . thank you very much

    0
  • Danny

    Monday, October 10th, 2011 03:12

    12

    is a dermazen ozon h2 o and h3 o system optimizasyon

    0
  • Daniel

    Friday, April 1st, 2011 10:30

    9

    Hi, thanks for the jQuery Tutorial – I’m currently getting into it as total Newbie in Java Script and your Tutorial helped me to get some first insights. Thanks, Daniel

    0
  • Kendy

    Tuesday, May 3rd, 2011 15:54

    10

    this is a great tutorial, I am a beginner and this is helping me get to understand jQuery very well. If anyone wanted to add the code to an external js here is how you do it:

    $(document).ready(
    function()
    {
    var headings = $(‘h3′),
    paras = $(‘p’);
    paras.hide().eq(0).show();

    headings.click(
    function()
    {

    // save the element that has been clicked for easy referal
    var cur = $(this);

    ////////// This section hides and shows with no animation ////////////////////
    // hide all the paragraphs
    /*cur.siblings(‘p’).hide();

    // get the next paragraph after the clicked header and show it
    cur.next(‘p’).show();*/
    ////////// This section hides and shows with no animation ////////////////////

    ////////// This section hides and shows with animation ////////////////////
    // hide all the paragraphs
    cur.siblings(‘p’).slideUp();

    // get the next paragraph after the clicked header and show it
    cur.next(‘p’).slideDown();
    ////////// This section hides and shows with animation ////////////////////
    });
    });

    just make sure that you link your html to your external js like this:

    0
  • Anna

    Wednesday, April 11th, 2012 06:12

    15

    Thanks a lot. It is cool. Explanation is dead easy compared to other sites

    0
  • gopi

    Friday, December 9th, 2011 13:17

    14

    hi,i want a code to validate a text box using jquery,,anyone pls send me the code …

    0
  • niaz

    Friday, December 2nd, 2011 18:13

    13

    this is very nice site, i have learned a lot about mobile website, wordpress plug in jquery . thank you very much

    0
  • Danny

    Monday, October 10th, 2011 03:12

    12

    is a dermazen ozon h2 o and h3 o system optimizasyon

    0
  • sunny

    Saturday, September 17th, 2011 12:25

    11

    Hi,

    how can I stop the already selected heading to again start the process of slideup and slidedown as
    I tried this

    headings.click(function() {
    var cur = $(this); //save the element that has been clicked for easy referal
    if (prevcur != cur) {
    cur.siblings(‘p’).slideUp(); //hide all the paragraphs
    cur.next(‘p’).slideDown(); //get the next paragraph after the clicked header and show it
    }
    var prevcur=cur;

    })

    but it didnt worked.

    +2
  • Kendy

    Tuesday, May 3rd, 2011 15:54

    10

    this is a great tutorial, I am a beginner and this is helping me get to understand jQuery very well. If anyone wanted to add the code to an external js here is how you do it:

    $(document).ready(
    function()
    {
    var headings = $(‘h3′),
    paras = $(‘p’);
    paras.hide().eq(0).show();

    headings.click(
    function()
    {

    // save the element that has been clicked for easy referal
    var cur = $(this);

    ////////// This section hides and shows with no animation ////////////////////
    // hide all the paragraphs
    /*cur.siblings(‘p’).hide();

    // get the next paragraph after the clicked header and show it
    cur.next(‘p’).show();*/
    ////////// This section hides and shows with no animation ////////////////////

    ////////// This section hides and shows with animation ////////////////////
    // hide all the paragraphs
    cur.siblings(‘p’).slideUp();

    // get the next paragraph after the clicked header and show it
    cur.next(‘p’).slideDown();
    ////////// This section hides and shows with animation ////////////////////
    });
    });

    just make sure that you link your html to your external js like this:

    0
  • Daniel

    Friday, April 1st, 2011 10:30

    9

    Hi, thanks for the jQuery Tutorial – I’m currently getting into it as total Newbie in Java Script and your Tutorial helped me to get some first insights. Thanks, Daniel

    0
  • NK

    Sunday, April 25th, 2010 01:08

    8

    thanks for sharing nice jquery thoughts….

    0
  • Web Risorsa

    Saturday, April 24th, 2010 11:16

    7

    Nice explanation… Looking for more of the same…

    0
  • Nikola Dadić

    Thursday, April 22nd, 2010 19:21

    6

    i think you forget to close some tags in first code

    0
  • obozdag

    Thursday, April 22nd, 2010 07:26

    5

    Easy to understand, useful, short article. Thanks.

    0
  • Negoita Cosmin

    Wednesday, April 21st, 2010 21:53

    4

    Nice article. It’s really simple! Thank you!

    0
  • Aisha

    Wednesday, April 21st, 2010 18:19

    3

    Beautiful Site, I really like it.

    0
  • Cook

    Wednesday, April 21st, 2010 17:45

    2

    a very well written article….

    0
  • Keiron Lowe

    Wednesday, April 21st, 2010 16:57

    1

    Fantastic, been waiting a while for the next bit of this series. Your really good at describing what the code does and such. Cheers

    0

Comments are closed.

54.225.57.156 - unknown - unknown - US