Documentation

Tutorials:jQuery For Designers

From jQuery JavaScript Library

Jump to: navigation, search

Examples of writing Unobtrusive JavaScript to add simple behavior to a web page.

Original: http://www.ok-cool.com/posts/read/1-jquery-for-designers-part-1
Author: Mark Panay

Similar Tutorials: SelectorsManipulationEffectsEvents

Contents

Part 1

I'm a bit funny when it comes to semantic markup. I really don't like putting visual cues into the markup that I may want to change later. You know those little symbols that we put at the end or beginning of a sentence, that we sometimes no longer use as literary symbols.

As an example, when I'm creating a form it pains me that I have to embed a colon into the markup at the end of the label text. We know why we do this, so that our input box has some kind of “stop” before it, making the view to the user just that little bit cleaner and easier on the eye. Then of course the client asks us if we can change the colon to a hyphen or a comma and we huff and puff because we've embedded these visual cues into the mark-up of all of our pages and doing a search and replace on a colon in an entire site can be a bit hit and miss at the best of times.

CSS to the rescue?

Those thoughtful folks from the W3C have given us the lovely pseudo classes of “:before” and “:after” that we can use to append or prepend content before or after an element. But as you may know these really useful tools are not featured in Internet Explorer. So what next?

Try JavaScript?

Nope, I'm a designer. I don't get it, it's ugly, it's not accessible, it's bad for usability and it'll bloat my page. Hmm.... OK.

Mythical widget

Let's pretend for a minute that there's this mythical widget thingy that we can put into our markup. It will do all sorts of clever things in a very easy manner without our having to be a programming wiz, and it won't damage our nice clean markup. Let's also assume that our mythical widget thingy looks like this:

 <script src="http://jquery.com/src/jquery-latest.js"></script>
 <script type="text/javascript">
   $(document).ready(function(){
     $("dd label").append(":");
   });
 </script>

OK, there's no fooling you. It's not mythical. See the example here. If you look at the source of the page you can see that there is no colon in the markup.

Firstly we include the jQuery JavaScript remotely purely for convenience. For speed reasons, I wouldn't recommend doing this in a runtime environment (it does mean that we are always using the latest version, though). Next we set up a function that looks for every label within every dd in the page and adds a colon inside the label at the end. This function doesn't do anything until the page is “ready”, which is decided by the last bit of JavaScript before we close the script tag.

What if we want to add a colon to the beginning of the element? We just use “prepend” instead of “append”, like so:

 $("dd label").prepend(":");

It couldn't really be any simpler, and we haven't even touched our beautiful markup.

Of course we want this to be sitewide, so we just put this JavaScript into a separate file and include this in every page.

 <script src="http://jquery.com/src/jquery-latest.js"></script>
 <script src="scripts/myjavascript.js"></script>

Now every page that has a dd element with a label will get a colon stuck on the end. When our client asks to change this we can do a very minor edit and the whole site is updated, just as it should be.

The downside to this technique is that the user needs to have JavaScript enabled, as the majority of users do. It's a risk that I'm prepared to take, and in this case it degrades quite nicely too.

As you can see, the power of jQuery is pretty phenomenal, and we haven't even scratched the surface. For more information on jQuery take a look at the jQuery homepage.

In Part 2 we'll look at a few more examples based on this technique. How about using an image instead of a colon? Or replacing the actual label text with an image? Or...?

Part 2

In our first look at jQuery we established that we could use jQuery to “fix” some of the discrepancies of certain browsers’ handling of CSS. We used jQuery to simply append (or prepend) a little bit of information inside a tag, enabling us to make sitewide changes to certain visual cues very quickly and simply.

With part 2 we are going in a little deeper. Most web sites these days tend to have “news” pages where they display a “title”, a “summary” and the main “body” of the article. To my mind this can sometimes lead to overwhelming amounts of text in your face. I don't know about you, but if I'm presented with masses of text my brain shuts down and orders my fingers to click my mouse button away.

Wouldn't it be nice…

Wouldn't it be nice to be able to have a little button underneath each article that displayed the “body” when it was needed and allowed just the summaries for each article to be shown in the meantime? Of course it would, and using jQuery we can do this very quickly and simply — a bit like this.

Diving in

Before we dive straight in, let's think about our lovely, accessible, semantically strict XHTML code for a few minutes. Our page already displays the “title”, “summary” and “body”, so we need to hide the body and place a “button” under the body. If we just placed a “button” directly into the page and the user has JavaScript turned off we would have a button that did nothing — bad usability. Hmm.

Bad button, bad

OK, so we need to add the “button” if JavaScript is enabled first. Now luckily we've already figured out how to do this in part 1. We just added the button using prepend in our JavaScript.

Show me the money...

So the first part of our JavaScript looks like this:

 <script src="http://jquery.com/src/jquery-latest.js"></script>
 <script>
   // When the page is ready
   $(document).ready(function(){
     $(".article .thebody").hide();
     $("#container .article ul")
       .prepend("<li class='readbody'><a href='' title='Read the article'>Read Body</a></li>");
   });
 </script>

If you've read the first part of this tutorial, this should look a little familiar. This assumes that our HTML mark-up looks like this...

 <div id="container">
   <div class="article">
     <h3>Title 01</h3>
     
     <p class="summary">Summary 01</p>
     <p class="thebody">Lorem ipsum....</p>
     
     <ul class="actions">
       <li><a href="">comment</a></li>
       <li><a href="">Trackback</a></li>
     </ul> 
     
   </div>
   
   <div class="article">
     <h3>Title 02</h3>
     
     <p class="summary">Summary 02</p>
     <p class="thebody">Lorem ipsum....</p>
     
     <ul class="actions">
       <li><a href="">comment</a></li>
       <li><a href="">Trackback</a></li>
     </ul>
   </div>
 </div>

So our JavaScript firstly hides everything with a class of .thebody making all of our “body” text disappear, then it finds the UL in .article and prepends an LI with a link that displays “Read Body” inside the UL.

This means that we hide all the article body text and stick another list item into every unordered list contained in an article. OK, that was easy (was it?), but now we have to delve into the deep, dark depths of JavaScript to get the functionality that we want.

 <script src="http://jquery.com/src/jquery-latest.js"></script>
<script> //<![CDATA[ // When the page is ready $(document).ready(function(){ $(".article .thebody").hide(); $("#container .article ul") .prepend("<li class='readbody'><a href='' title='Read the article'>Read Body</a></li>"); $(".actions li.readbody a").click(function(event){ $(this).parents("ul").prev(".thebody").toggle(); // Stop the link click from doing its normal thing return false; }); }); //]]></script>

Dark and Deep?

EH? OK, so it's not as dark and deep as we thought, but it's still pretty mysterious nonetheless. Essentially, this new bit of code looks for the link that we've just added and then steps back through the HTML until it finds the class .thebody. If it finds this, it gets toggled on or off and the default action of being a link is disabled (so we don't click away or reload the page).

Try it by clicking one of the "Read Body" links in the following sample articles:

Title 01

Summary 01

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla viverra aliquet mi. Cras urna. Curabitur diam. Curabitur eros nibh, condimentum eu, tincidunt at, commodo vitae, nisi. Duis nulla lectus, feugiat et, tincidunt nec, iaculis vehicula, tortor. Sed tortor felis, viverra vitae, posuere et, ullamcorper a, leo. Suspendisse euismod libero at orci. Pellentesque odio massa, condimentum at, pellentesque sed, lacinia quis, mauris. Proin ultricies risus cursus mi. Cras nibh quam, adipiscing vel, tincidunt a, consequat ut, mi. Aenean neque arcu, pretium posuere, tincidunt non, consequat sit amet, enim. Duis fermentum. Donec eu augue. Mauris sit amet ligula.

Title 02

Summary 02

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla viverra aliquet mi. Cras urna. Curabitur diam. Curabitur eros nibh, condimentum eu, tincidunt at, commodo vitae, nisi. Duis nulla lectus, feugiat et, tincidunt nec, iaculis vehicula, tortor. Sed tortor felis, viverra vitae, posuere et, ullamcorper a, leo. Suspendisse euismod libero at orci. Pellentesque odio massa, condimentum at, pellentesque sed, lacinia quis, mauris. Proin ultricies risus cursus mi. Cras nibh quam, adipiscing vel, tincidunt a, consequat ut, mi. Aenean neque arcu, pretium posuere, tincidunt non, consequat sit amet, enim. Duis fermentum. Donec eu augue. Mauris sit amet ligula.

Title 03

Summary 03

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla viverra aliquet mi. Cras urna. Curabitur diam. Curabitur eros nibh, condimentum eu, tincidunt at, commodo vitae, nisi. Duis nulla lectus, feugiat et, tincidunt nec, iaculis vehicula, tortor. Sed tortor felis, viverra vitae, posuere et, ullamcorper a, leo. Suspendisse euismod libero at orci. Pellentesque odio massa, condimentum at, pellentesque sed, lacinia quis, mauris. Proin ultricies risus cursus mi. Cras nibh quam, adipiscing vel, tincidunt a, consequat ut, mi. Aenean neque arcu, pretium posuere, tincidunt non, consequat sit amet, enim. Duis fermentum. Donec eu augue. Mauris sit amet ligula.

And that's it. We've modified our existing site to use a nice, accessible piece of JavaScript to enhance the site's usability. You'll notice as well that we've enclosed the JavaScript in a CDATA tag. This prevents XHTML validation systems from throwing a wobbly and allows the page to validate for strict compliance.