Basic AJAX Tutorial: jQuery toggle and slide

Wednesday, January 21st, 2009 | Business, Tutorials | by

In this tutorial we will review:

  • Definition of AJAX
  • Introduction to jQuery
  • Basic document jQuery preparation
  • Binding jQuery actions to an anchor (A) tag
  • Toggling visibility of a div
  • Sliding in and out of that div

It sounds like a lot, but it’s all very easy.

Definition of AJAX
The term AJAX means Asynchronous JavaScript and XML.  That means AJAX technically defines a method for javascript to communicate with XML.  Over the past few years AJAX has been interpreted as a means for implementing all “web 2.0” functionality in the front end.  That added things like animations to the general term “AJAX”.




Introduction to jQuery
jQuery is one of my favorite libraries with a good toolset for working with AJAX techniques.  You can find out more information on jQuery at their site.

jQuery is a “fast and concise Javascript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development”.  Taken from the website itself.

As a javascript library, we will have to include the jQuery library on a page, and implement some of it’s more basic functions.

Basic jQuery document preparation
The first thing we need to do is incorporate the jQuery library in our page.  So download jQuery (direct link to the Google Code location).

Now that we have our JS library, we need to tell our document where it is (I renamed my js file to jquery.js, and threw it in the js folder):

<html>
<head>
     <script language="javascript" src="js/jquery.js"></script>
</head>
<body>

</body>
</html>

We inserted the SCRIPT tag to include the jquery library when the page is loaded.

Binding jQuery actions to an anchor (A) tag
Lets create a basic link in our document:

<html>
<head>
     <script language="javascript" src="js/jquery.js"></script>
</head>
<body>
     <a href="#">Click Here</a>
</body>
</html>

We now have a link that does nothing.  We are preparing to bind jQuery to the anchor.

Toggling the visibility of a div
We need to do 2 things to toggle the visibility of a div with jQuery.  First off, we need a DIV to toggle!  Second we need to bind jQuery commands to the anchor link.

We will take advantage of the jQuery toggle effect.

To do this, we change our code below:

<html>
<head>
     <script language="javascript" src="js/jquery.js"></script>
     <script language="javascript">
     $(document).ready(function() {
          $('#toggleButton').click(function() {
               $('#toggleSection').toggle();
               return false;
          });
     });
     </script>
</head>
<body>
     <a href="#" id="toggleButton">Click Here</a>
     <div id="toggleSection">
          Content to toggle on and off
     </div>
</body>
</html>

This step we did a lot.

First we added [id=”togglebutton”] to the A tag.  That lets us identify it in the jQuery code.

Second we added the “toggleSection” DIV to the document.  The entire div will be toggled on and off.  Again, here we identified the DIV as “toggleSection” to be able to target it with the jQuery code.

Third, we added the jQuery code that actually does the toggling in the HEAD section of the document.  jQuery is a javascript engine, so we have to execute the commands in SCRIPT tags.  The first line of the code, “$(document).ready(function() {” is complicated.  Lets dissect this code.

Finally we put “return false;” in the code, that tells the link NOT to use the HREF value.  This means “#” will not be loaded.  It’s annoying, because that brings the browser to the top of the page in certain browsers.

$(document) — this is the HTML document itself.  It is the same as “document” in normal javascript.

.ready( — this is us looking at the “onLoad” part of jQuery.  When the document is ready, it executes  the “ready” method.  Here we are defining what the ready method is.

function () { — basically, we are creating a new function that will fill in for the document.ready method.  When the document is ready, our code will be executed.  This is smart, as executing code when the page isn’t ready can result in missing elements that aren’t loaded yet.

After that statement, we have “$(‘#toggleButton’).click(function() {“, another complicated statement.  Lets break it down:

$(‘#toggleButton’) — we are looking for the “toggleButton” via jQuery.  This code finds it for us.

.click( — Instead of setting the value of the “ready” method before, we are setting the function of when the “toggleButton” is clicked. So we need to create a function…

function () { — again, creating a function inline.  This will be assigned to the button’s “click” method.

Finally we do the fun stuff, toggling the DIV on and off with “$(‘#toggleSection’).toggle();”.  By now it should be easier to read this line.  We are finding the toggleSection div, and calling the jQuery method of “toggle()” which will toggle the visibility of the DIV.

It is important to note the “return false” part of this.  By returning false, we are telling the HREF that it should NOT execute the HREF value (which is #, and would bring the browser to the top of the screen).  If we don’t return false, the browser will still load the HREF value, and we will have some minor issue cross browser.

We’re done!  We are toggling the visibility, check out the demo — jQuery toggle demo.  Fortunately, we can still have a little more fun..

Sliding in and out of that div
In the previous step, we toggled the visibility of a DIV.  It’s not too exciting, as we could easily do that with javascript before with stylesheets and basic DOM code.  What is great about the jQuery library is all of the additional methods for animation it gives us.  Lets setup that div to not just appear, or hide — but to slide in and slide out.

For that we will take advantage of the slideUp and slideDown methods, they are just 2 of many Effects available in jQuery.

<html>
<head>
     <script language="javascript" src="js/jquery.js"></script>
     <script language="javascript">
     $(document).ready(function() {
          $('#toggleButton').click(function() {
               if ($('#toggleSection').is(":hidden"))
               {
                    $('#toggleSection').slideDown("slow");
               } else {
                    $('#toggleSection').slideUp("slow");
               }
               return false;
          });
     });
     </script>
</head>
<body>
     <a href="#" id="toggleButton">Click Here</a>
     <div id="toggleSection">
          Content to toggle on and off<br>
          More content<br>
          Slides are more fun with more content<br>
          Four lines should be enough
     </div>
</body>
</html>

We have added a little more content to the DIV, so we can more easily see how the slideUp and slideDown work.  There are 2 interesting steps we hav taken.

First, we added an “if” statement to detect if the DIV is hidden or not.

Second, we added code to slideUp or slideDown depending on whether the DIV is actually hidden.

Check out the result on our example — jQuery slideUp and slideDown demo.

Conclusion
I hope this helped some of you out.  Let me know if it did.  Comments are open!

Related Posts

Tags: , , , , , , , , , , , , ,

20 Comments to Basic AJAX Tutorial: jQuery toggle and slide

Jarrod Gordon
January 21, 2009

Very interesting… thanks for the post.

PaulN
April 21, 2009

Thank you for this basic information.
I use the script.aculo.us scripts for a sliding-effect on a categories-overview-page. One click on the title slides the complete post in and makes it visible.
The script.aculo.us are bigger than the jQuery, so i would like to switch to jQuery for my categories-overview.
I don’t understand how i can use a link with a variable like <a href=”#” onclick=”Effect.toggle(‘postfull-‘, ‘slide’, {duration:0.1}); return false;”> in jQuery and how do i tell the script the_ID()?
I think that this is possible with the jQuery too, or not?

seangw
April 22, 2009

Scriptaculous is much bigger. jQuery has been pretty lean, maybe because they both started off at separate ends of the AJAX spectrum?

You can use a variable, I’m assuming you meant to write “postfull-‘+the_ID()” or something like that?

There are a handful of ways to do it, you can write the HTML itself using:

document.write("<a href=\"#\" onclick=\"Effect.toggle(’postfull-’" + the_ID() + ", ’slide’, {duration:0.1}); return false;\">");

Maybe you just want it simpler than that, no reason you can’t include the variable in the HTML to begin with:

<a href=”#” onclick=”Effect.toggle(’postfull-’ + the_ID(), ’slide’, {duration:0.1}); return false;”>

Does this help you out?

paul
May 4, 2009

This is a cool effect. Just FYI though, this example does not use Ajax. It’s a Javascript effect, executed through Javascript manipulation of the page (CSS, DOM, etc.). Ajax means you’re pulling some data into the page without reloading the whole page. In jQuery this is done via these methods – http://docs.jquery.com/Ajax – or XMLHttpRequest in regular Javascript.

seangw
May 4, 2009

Thanks Paul

As I say in the beginning of the article, AJAX technically “defines a method for javascript to communicate with XML. Over the past few years AJAX has been interpreted as a means for implementing all ‘web 2.0’ functionality in the front end. That added things like animations to the general term ‘AJAX’.”

You are right, AJAX technically is solely javascript talking with data (as traditional server side languages once used to be the sole method for accessing data). It’s just that AJAX is so closely associated with animation packages that are frequently required to display the vastly larger amount of information a web page can actively display without a page request.

It’s a concession us web developers have to make, accepting that some of our “technical” terms have had incorrect definitions applied by the common though processes.

I’d love to help coin a more correct term, but it’s quite the uphill battle.

Adam
May 8, 2009

Hi Sean –

I’m not certain what I’m missing. I’m using this method to show/hide a portion of a form. The “show” feature works, but not the “hide.” I am wrapping the toggleSection div around a fieldset element in the form. Any thoughts?

Thanks.

Kung CL
June 15, 2009

Is it possible to make content hidden by default, show up on clicking “Click Here ” ?

seangw
June 15, 2009

Of course it is! Try figuring it out on your own, it’ll help you understand more about what you are doing.

Sometimes I feel like people search the internet not to help themselves figure something out, but to hope to find the right code snippet that works for whatever they are working on. It should be easy to put together the right code to do what you are asking. I’d rather answer questions like “why this” or “I tried this, but it didn’t work” then have someone ask for the exact code they are looking for.

Jeff Coughlin
July 9, 2009

Wouldn’t it be easier to just use the one line:
$(‘#toggleSection’).slideToggle(600);

instead of the multiple lines:
if ($(‘#toggleSection’).is(“:hidden”))
{
$(‘#toggleSection’).slideDown(“slow”);
} else {
$(‘#toggleSection’).slideUp(“slow”);
}

And Kung, try using the hide function (or just use CSS to preset display:none on the element)
$(‘#toggleSection’).hide();

Levi
November 3, 2009

Thanks! This helped me with a website.

Roger
February 26, 2010

Is it possible to manipulate the Click here where when show it shows a – button and to show it shows a + button? Or would that be done via CSS?

seangw
February 27, 2010

I’m not sure what you are asking? Do you want to collapse items onclick? It sounds like something that would be both CSS and a bit of jQuery.

[…] Basic AJAX Tutorial: jQuery toggle and slide – Includes AJAX definition, Introduction to jQuery […]

shiva
May 12, 2010

Hi, thanks a lot, this is good exampls

Mike
June 22, 2010

Your post reminds me to my old post three years ago in which I encouraged people to use jQuery (you can read it here: http://tech.amikelive.com/node-22/7-reasons-to-use-jquery-as-the-javascript-framework-in-your-web-20-apps/)

It also seems that the div visibility issue is popular for jQuery users. When I read your example, I reflected to mine 😀

Anyway, it’s nice to know how jQuery has been gaining more popularity these days.

Dmitry
October 14, 2010

Very useful information, thank you.

web design
February 14, 2011

nice post man…thanks for sharing this….

Andy
June 28, 2011

I’m having trouble getting this to toggle. Must have something to do with where the toggle link is placed. I’m getting the effect, but it only slides down. The div won’t slide back up–just keeps repeating the slide down. Any idea? Thanks.

Mark
February 9, 2012

Very well described and got it to work exactly as I needed in the RAILS project I am currently working – thanks a lot!

Peter Vietnam
July 3, 2012

Great recourse of information. This helps making more features of the website in easy way.

Leave a comment

*


Please share, it makes me happy:

Subscribe to Email Alerts

Follow Me

Follow seangw on twitter

Archives

Categories

prestashop theme

virtuemart template