Registration for jQuery Conference 2008 is closed.

Beginner Entries

Scroll Up Headline Reader

Saturday, October 14th, 2006

A couple weeks ago someone on the jQuery discussion list asked if someone could reproduce a rotating headline box in which the headlines, in succession, scroll up into the box, pause, and then scroll up out of the box. Since I already had some code for rotating images on a page, I decided to recycle it and take the challenge.

Here is the finished product. (Please note that if you are looking at this in a feed reader, you won’t be able to see the effect. )

(more…)

Fancy Drop Cap - Part 2

Monday, October 2nd, 2006

In Fancy Drop Cap - Part 1, I showed how I used jQuery to insert a drop cap on my personal weblog. But there is still some unfinished business to take care of:

  1. Accounting for cases in which the first paragraph (where I want my drop cap to go) starts with another tag of some sort (<a href="...">, <em>, etc.)
  2. Adding a little CSS to the drop cap

So let's begin with item 1. As you may recall, we defined three variables, first_paragraph, first_letter, and text. The variables allowed us to get the value of the textNode of the first letter of the first paragraph, so we could replace it with the image. Here is what that part looked like:

JavaScript:
  1. var first_paragraph = $('#main-content p')[0];
  2. if (!first_paragraph) return false;
  3. var text = first_paragraph.firstChild.nodeValue;
  4. var first_letter = text.substr(0,1);
  5. if ( text ) {
  6.   first_paragraph.firstChild.nodeValue = text.slice(1);
  7. }

The only problem with that code is that line 3 assumes that the first child node of the first paragraph is actually a text node. But what if it's a span tag (<span>) or a link (<a href="...">)? Well, in that case we'll need to keep drilling down through the nodes until we can't go any farther.

Loop the Loop

To do that, we'll set an intermediate variable, called node, initially making it the same as first_paragraph:

JavaScript:
  1. var node = first_paragraph;

Next, we change our node variable to be defined as the first child of that node (node = node.firstChild), and we keep doing that until there are no more child nodes left, by using a "while" loop:

JavaScript:
  1. while (node.childNodes.length) {
  2.   node = node.firstChild;
  3. }

So, in other words, as long as there is a child node, our variable will be reset as that child node.

The First Letter — and Only a Letter

When that's all done, we set our text variable, this time as the value of our node variable:

JavaScript:
  1. var text = node.nodeValue;

Now all we have to do is get the first letter of the text so that we can replace it with the drop-cap image: var first_letter = text.substr(0,1).

There is just one more thing that we should account for (more...)

Fancy Drop Cap - Part 1

Wednesday, September 20th, 2006

Introduction

Last spring when I implemented a new design for my weblog, I wanted to use a fancy drop cap for the first letter of the first paragraph of the first post of each page. There are all sorts of ways to make a drop cap happen, but since I was reading Jeremy Keith's excellent book DOM Scripting at the time, I thought I'd do it that way. The DOM scripting method that I put together had some important benefits for me at the time:

  • It used an image, so I didn't have to worry about installed fonts on users' machines
  • The HTML source stayed intact, so search engines wouldn't trip over a first word with a missing first letter.
  • It degraded nicely, so if users had JavaScript or images or both turned off, everything would still look fine, just a little less pretty.

Now that I'm learning jQuery, I thought I'd revisit my code and see if I could tidy it up a bit, the jQuery way.

Image Set

AI first put together a set of images, one for each letter of the alphabet, using a font from the Dieter Steffman collection at typOasis. If you don't want to go through the laborious process of converting letters into images, you can download mine (20KB zip). See the letter "A" floating to the right of this paragraph for an example.

Setting up the Code

Instead of putting all of the code in a $(document).ready() function, I created a separate function and just called it inside $(document).ready():

JavaScript:
  1. $(document).ready(function() {
  2.   swap_letter();
  3. });
  4.  
  5. function swap_letter() {
  6.   //all the code goes here
  7. }

Now we can get down to business.

Insert Image Here

The easiest part of the process was inserting the image, because jQuery makes it almost effortless.

(more...)

Slicker Show and Hide

Monday, September 11th, 2006

Last time I showed you how to make something appear and disappear on a web page. This time I'll show you how to do it with style.

Like we did last time, we'll start with our $(document).ready() and put everything else inside of it.

Adjust the Speed

This time, however, we're going to adjust the speed at which our item shows and hides. To do so, we put a speed indicator — "slow" or "normal" or "fast" or a number of milliseconds (1000 = 1 second) — inside the parentheses:

JavaScript:
  1. $('#slickbox').show('slow');

Note: If you use a speed word, put it inside quotation marks (either single or double); if you use a number, omit the quotation marks: $('#slickbox').show(500);

Attach Effects to Events

The final step here is to attach the effects to events. Last time we attached our effects to the "onclick" event of buttons. This time we'll attach them to links. But here's the rub: Links already have events attached to them. They take the user to whatever URL is indicated in the "href" attribute, usually another page. That means that we not only need to make something happen, but we also need to stop the default thing from happening. We can prevent the default behavior by adding return false;.

So let's take a look at how we would tie the "onclick" event of one link with an ID of "slick-show" to the "show" effect. Here, show() will display a DIV with an ID of "slickbox":

JavaScript:
  1. // shows the slickbox DIV on clicking the link with an ID of "slick-show"
  2.   $('a#slick-show').click(function() {
  3.     $('#slickbox').show('slow');
  4.     return false;
  5.   });

Notice that we attach ".click()" to "a#slick-show". In jQuery, events will often have anonymous, or lambda, functions inside them. That's why inside the parentheses of ".click()" you see function() { ... }. By the way, it's called an anonymous function because it has no name associated with it. I don't know why it's also called a lambda function. Can someone enlighten me?

Here is the final code for three effects — show(), hide(), and toggle(). I've added $('#slidebox').hide() as the first line after $(document).ready() to hide that DIV when the page loads.

JavaScript:
  1. $(document).ready(function() {
  2.  // hides the slickbox as soon as the DOM is ready
  3.  // (a little sooner than page load)
  4.   $('#slickbox').hide();
  5.  
  6.  // shows the slickbox on clicking the noted link 
  7.   $('a#slick-show').click(function() {
  8.     $('#slickbox').show('slow');
  9.     return false;
  10.   });
  11.  
  12.  // hides the slickbox on clicking the noted link 
  13.   $('a#slick-hide').click(function() {
  14.     $('#slickbox').hide('fast');
  15.     return false;
  16.   });
  17.  
  18.  // toggles the slickbox on clicking the noted link 
  19.   $('a#slick-toggle').click(function() {
  20.     $('#slickbox').toggle(400);
  21.     return false;
  22.   });
  23.  
  24. });

Look closely at the code and you'll see that our slickbox will show at a slow speed, hide at a fast speed, and toggle somewhere in between (in 400 milliseconds).

Demo 1

Try it out for yourself. Just click on the three following links:

Show the box  Hide the box  Toggle the box

This is the box that will be shown and hidden and toggled at your whim. :)

Newbie Tip

For those of you brand new to JavaScript as well as jQuery, the lines of code that begin with two slashes ( // ) are comment lines that have no effect on the code whatsoever. You can also create multi-line comments by enclosing them in /* and */

Other Effects

Other simple jQuery effects for showing or hiding elements include:

  • slideUp()
  • slideDown()
  • slideToggle()
  • fadeIn()
  • fadeOut()

Demo 2

Try the slide effects to see how they differ from show/hide:
Slide the box down  Slide the box up  Slide toggle the box

Bonus

For more sophisticated effects, check out Stefan Petre's Interface plugin

UPDATE

If this type of showing and hiding isn't exactly what you're looking for, please check out my other entries and Jörn Zaefferer's accordion menu plugin:

Basic Show and Hide

Wednesday, September 6th, 2006

As promised in my last entry, I'll be showing you a simple effect that you can do using jQuery: showing or hiding something, or a group of things, on the page. The two functions that let us do this are, not surprisingly, show() and hide().
jQuery also comes with another function called toggle(), which will make matching elements visible if they are hidden or hidden if they are visible.

So, let's get down to business. We're going to start with our $(document).ready() function.

JavaScript:
  1. $(document).ready(function() {
  2.   // we'll put our code here
  3. });

Next, we'll choose what we want to show or hide. Hmm, let's see. How about the site's title? Excellent! Now, whenever we refer to an element in jQuery, we start with the dollar sign, $, and we put any CSS or XPATH selector in parentheses right after it: $('css-selector')

Since the site's title is wrapped in an <h1> tag, we'll refer to it this way: $('h1'). We could just as easily refer to all DIVs with a class of "treacle" — $('div.treacle') — or any paragraph that is a chlid of a DIV with an ID of "bonespur" — $('#bonespur > p').

Now for the magic. To make the site's title disappear, we just connect $('h1') and hide() with a dot (.) and stick it all inside the $(document).ready() like so:

JavaScript:
  1. $(document).ready(function() {
  2.   $('h1').hide();
  3. });

The code above will make the site's title hide when the DOM / page loads, which isn't ideal for our purposes here, so I'm going to attach the the hide() event to the first button below instead. The second and third buttons will handle show() and toggle() respectively.

Just for kicks, we'll show and hide this sentence, which is wrapped in a div with class="showhide", too.

How did I attach the hiding and showing to those buttons? I'll show you that in my next entry.

Multiple $(document).ready()

Tuesday, September 5th, 2006

One more great thing about $(document).ready() that I didn't mention in my previous post is that you can use it more than once. In fact, if you don't care at all about keeping your code small, you could litter your javascript file with them.

It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain free.

You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready(). So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so:

HTML:
  1. <script src="/js/jquery.js" type="text/javascript"></script>
  2. <script src="/js/common.js" type="text/javascript"></script>
  3. <script src="/js/homepage.js" type="text/javascript"></script>

You could also do something like this inside a single .js file:

JavaScript:
  1. $(document).ready(function() {
  2.   // some code here
  3. });
  4.  
  5. $(document).ready(function() {
  6.   // other code here
  7. });

A final note: In a comment to my previous post, Jörn gave this excellent tip for shrinking your code:

Even for this little amount of code is a shortcut available:

$(function() {
// do something on document ready
});

A function passed as an argument to the jQuery constructor is bound to the document ready event.

Coming Up: In my next entry, I'll show how to do a simple effect with jQuery. You'll be amazed at how easy it is!