jQuery – What a marvel

WOW!

This is going to be BIG. I am very very impressed. (It happens a lot – I am generally too busy to keep up with the developments)
Glad Justin got me interested…

Let’s see if we have the facts straight here..

Introduction

Very good intro document written by John Resic “Tutorial: How jQuery works”

Instead of using the standard windows.onload() event to get your code up and running, jQuery comes with a better solution that does not force you to wait for all your images to load. This one fires as soon as the document is ready to do something.

$(document).ready(function(){
  // Your code here
 });

Now let’s see this in action. Suppose your HTML document looks like this:

<body>
<a href=”http://jquery.com“>jQuery</a>
</body>

You will be able to catch the click event and even override the default behavior like this in the jScript code:

$(”a”).click(function(event){
    event.preventDefault();
    alert(”Thanks for visiting!”);
    alert(”This is my alert”);
});

Adding a class
Another thing that is a common task is the addition (or removal) of classes from elements, for example:

$(”a”).addClass(”test”);

if you were to add some style information into the header of your script, like this:

<style type=”text/css”>a.test { font-weight: bold; } </style>

and then added the above addClass call – all your A elements would now be bold. To remove the class, you’d use removeClass

Special Effects
In jQuery, a couple handy effects are provided, to really make your web site stand out. To put this to the test, change the click that you added earlier to this:

$(”a”).click(function(event){ 
    event.preventDefault(); 
    $(this).hide(”slow”); 
}); 

Now, if you click any link, it should make itself slowly disappear.

Chain ability (The Magic of jQuery)
jQuery uses an interesting concept to make its code short and simple. For those familiar with object-oriented programming, this concept should be rather straightforward.

In a nutshell: Every method within jQuery returns the query object itself, allowing you to ‘chain’ upon it, for example:

$("a").addClass("test").show().html("foo");

Each of those individual methods (addClass, show, and html) return the jQuery object, allowing you to continue applying methods to the current set of elements.

Example: Collapsing individual chapters – let’s assume our HTML code looks like:

<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>

And our jQuery looks like:

<script src=”http://jquery.com/src/jquery-latest.js“></script>

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 (wasn’t 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>

Switching style sheets

Example here

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
<title>jQuery Demo</title>
<link rel=”stylesheet” type=”text/css” media=”screen” href=”Normal.css” />
</head>
<body>
<h1>Choose A Style:</h1>
<ul>
<li><a id=”StyleContrast” href=”#”>Contrast</a></li>
<li><a id=”StylePrint” href=”#”>Print</a></li>
<li><a id=”StyleNormal” href=”#”>Normal</a></li>
</ul>
</body>
</html>

And in jquery:

$(”#StyleContrast”).click(function() {
   $(”link[media='screen']“).attr(”href”, “Contrast.css”);
});

$(”#StylePrint”).click(function() {
   $(”link[media='screen']“).attr(”href”, “Print.css”);
});

$(”#StyleNormal”).click(function() {
   $(”link[@media='screen']“).attr(”href”, “Normal.css”);
});

Type your search here
A small script, which populates a form-field with a default text as description. This text will clear if the input is in focus and repopulate if the focus is lost without any input.

<form action=”#” method=”post”>
<input id=”SearchText” name=”text” />
<button>Search
</form>

As this task may be used in different situations, it’s a good idea to write a reusable function for it. The first parameter is a selector (in our case "#SearchText" but something like "input[@name=search]" might be usefull too), the second parameter is the default value of that input element (e.g. "Enter your search term here..").

function populateElement(selector, defvalue) {
if($.trim($(selector).val()) == “”) {
$(selector).val(defvalue);
}

$(selector).focus(function() {
if($(selector).val() == defvalue) {
$(selector).val(”");
}
});

$(selector).blur(function() {
if($.trim($(selector).val()) == “”) {
$(selector).val(defvalue);
}
});
}

In our special case the Javascript might look like this:

populateElement(’#SearchText’, ‘Enter your search term here..’);

To prevent giving non-javascript users a hard time with deleting default values manually, we write the default-value with javascript, without using the value=".." attribute of <input>

Checking browser family

if ($.browser.msie) {
// Internet Explorer is not that good at CSS
}

This one will come in handy at http://lyngbytaekwondo.dk – we always have issues with browser compatibility there…