Playing with jquery



«  ♥  »


Posted on June 27, 2011 | Published in jQuery Tuts

Before I decided to switch to jQuery, I was using the Prototype JavaScript library combined with Motools in all my projects, they were kinda cool, it took me some days to learn but it was cool! But, about a year ago, I heard about a cooler library that was much more easier to learn and to use that Prototype. That framework is jQuery, so I’ve decided to give it a try. I downloaded a copy form the official website, took a quick look at the source code and the documentation, and then wrote my first line of jQuery, it was:

1
var _name = $('#name').val();

I was very surprised and happy because of two reasons:

  1. Because of PHP, I was used to write the $ symbol,
  2. And because I was able to put CSS selectors inside the $(‘…’) block

And since then, I somehow felt in love with this library, and this is why I decided to share with you my experience so you can « write less, do more ». I will try to keep this tutorial as simple as possible, so beginners won’t feel lost, and I promise those of you who are looking for more advanced techniques that I will put more tutorials about some advanced tricks as soon as I can.

But now let me give you a quick « foretaste » of what jQuery allows you to do!

1 Installing jQuery

The simpliest way to bring all the power of jQuery into your website, is to get the latest version from Google CDN:

1
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

And of course, if you don’t like this method, you can still download a copy from the jQuery website, copy it on your server and:

1
<script src="/path/to/jquery.js"></script>

And make sure to put that script tag above all of your other custom scripts that are using jQuery, of course for obvious reasons! like so:

1
2
3
4
5
6
7
8
9
10
11
12
< ! doctype html>
<html>                                                                  
 <head>                                                                  
 </head>
 <body>
   <!-- your normal html tags here -->
   <script src="/path/to/jquery.js"></script>  
   <script>
     // your code geos here
   </script>
 </body>                                                                
 </html>

2 Wait for the DOM

The first thing you need to keep in mind when using jQuery, and more generally when writing JavaScript code that manipulates the DOM tree, YOU HAVE to wait until to DOM is ready to invoke your actions! Otherwise, your code might not work at all: because the DOM tree is still not ready !

To do so, all you need is to wrap all your JavaScript code inside this block:

1
2
3
jQuery(document).ready(function(){
  // ...
});

And because jQuery is awesome, you can simply use the short hand code:

1
2
3
$(function(){
  // ...
});

Just keep in mind that $ === jQuery . Right?

3 Traversing the DOM

Finding and selecting an element is a way to simple when using jQuery. In fact, jQuery uses two techniques that allow you to find and select elements on your page:

  1. The first one is based on CSS selectors combined with XPath
  2. The second one uses several jQuery methods

And of course you can combine the two techniques as you like!

Let’s say you have the following page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
< ! doctype html>
<html>                                                                  
 <head>                                                                  
 </head>
 <body>

   <h1>Title</h1>

   <ul id="menu">
     <li><a id="my-link-1" class="all-links" href="/some/url/1" target="_blank">click me!</a></li>
     <li><a id="my-link-2" class="all-links" href="/some/url/2">click me!</a></li>
     <li><a id="my-link-3" class="all-links" href="/some/url/3">click me!</a></li>
     <li>
        <ul>
           <li><a id="my-link-4" class="all-links" href="/some/url/4">click me!</a></li>
        </ul>
     </li>
   </ul>

   <p>Description ...</p>
   
   // jquery scripts ...
 </body>                                                                
 </html>

In order to select the unordered list, in vanilla JavaScript you could write:

1
var _menu = document.getElementById("menu");

Well in jQuery, it looks like this:

1
2
3
4
$(function(){
  var _menu = $('#menu');
  // now you can access and modify all available _menu attributes and events
});

Simple, isn’t it? Let’s explain a bit what we did here.

We used a CSS selector #menu which, as you might know it, looks for an element that has the ID #menu and selects it. So, we used this, as a parameter of the jQuery constrctor. In fact, as I said earlier, the $ symbol is an alias to the jQuery class, thus the $(…) is the jQuery constructor. And by the why, $(‘#menu’) is called a jQuery selector.

Next, let’s say we want to add a CSS class “menu-links” to all the links that are available inside the menu; to do so:

1
2
3
4
5
6
7
8
9
10
11
$(function(){
  // method one
  $('#menu a').addClass('menu-links');

  // method two
  $('.all-links').addClass('menu-links');

  //method three
  $('#my-link-1, #my-link-2, #my-link-3, #my-link4')
     .addClass('menu-links');
});

Of course, given our example, I highly recommend the use of the second method! But in most cases, the first method works fine as well.

Now, we want to add a CSS class to all the direct children of the menu list:

1
2
3
$(function(){
  $('#menu > li').addClass('direct-children');
});

To demonstrate the use of XPath selectors, let’s say that you want to highlight all anchors that have a target attribute:

1
2
3
$(document).ready(function() {
   $("a[target]").addClass('highlight');
 });

Now, let’s say we want to add css class to all direct list items of the menu that have no unordered list children:

1
2
3
$(function() {
   $('#menu').find("> li").not(":has(ul)").addClass('all-li-but-ul');
 });

As you can see, I used the jQuery find() method that basically allows you to further search the descendants of the already selected elements, the menu. But just keep in mind the following statement:

1
2
3
4
5
6
7
8
$(function() {
    // method one
    $('#menu').find("> li").not(":has(ul)").addClass('all-li-but-ul');

    // method two
    $('#menu >  li").not(":has(ul)").addClass('all-li-but-ul');

 });

Method one and method two are mostly the same, however I encourage you to use method one because it is a bit more efficient than the second one!
But for now just forget about perfomance, we will discuss the performances issues later in further tutorials. For now just have fun with jQuery :)

4 Handling events

Because JavaScript is an event-driven programming language, let’s see how jQuery lets you observe and trigger events inside your code.

Given the same example page of the previous section, we want to add a CSS class and remove it when we hover the 2nd direct list item:

1
2
3
4
5
6
7
$(function() {
   $('#menu > li:eq(1)').hover(function() {
     $(this).addClass('hovered');
   },function(){
     $(this).removeClass('hovered');
   });
 });

NOTE: please note the $(this) notation, the “this” key word represent the element that is being hovered.

If you want to disable the default click action of all the links, try this:

1
2
3
4
5
$(function(){
  $('a').click(function(e) {
   e.preventDefault();
  });
});

And if you want to prevent a form with the ID #my-form from submitting your data, here is how you should do it:

1
2
3
4
5
$(function(){
  $('form#my-form').submit(function(e) {
   e.preventDefault();
  });
});

This is mostly the same piece of code like above. And more generally, you can use most of JavaScript events like so!

For instance, if you want to check if your users enter a strong password (for the sake of this tutorial, we are going to check the password length only!). To do so, you would have to use the onkeyup event. In jQuery, you can write this:

1
2
3
4
5
6
7
8
9
10
11
$(function(){
  $('input#my-password').keyup(function() {
   var text = $(this).val();
   if ( text.length < = 8 ) {
    $(this).addClass('weak-password');
   }
   else {
    $(this).removeClass('weak-password');
   }
  });
});

Or, let’s say you want to get the current mouse position and do some cool stuff with, you will proceed like so:

1
2
3
4
5
6
7
$(function(){
 $('#menu-2 > li').filter(':last-child').mousemove(function(e){
  $(this).text('Mouse X: '+e.pageX+', Mouse Y: '+e.pageY);
 }).mouseleave(function(){
  $(this).text('Move your mouse here!');
 });
});

So, here what we are doing is attaching two event handlers to the last list item of the #menu-2. The first event is the mouse move event - mousemove - this event is triggered every time you move the mouse inside the selected element. Then, we take advantage of the reference to the event that is being triggered in order to get the current mouse position.
The second event that we attached to the selected element is the mouse leave event - mouseleave -

So, I hope you get the idea!

5 Talking AJAX

Using AJAX with jQuery is really really simple. Let me give you an example.

1
2
3
$('#load-ajax-html').bind('click', function(){
 $('#ajax-html').load('lorem.html');
});

The load() method loads the content from the lorem.html file asynchronously and appends the result to the #ajax-html element.

jQuery offers many other AJAX methods, but most of them if not all, uses the low-level interface method $.ajax(). This method takes many parameters as you can see from the documentation page!

In order to illustrate a simple use of this method, let's write again the previous example:

1
2
3
4
5
6
7
8
9
10
$('#load-ajax-html').bind('click', function(){
 $.ajax({
  url:'lorem.html',
  type:'GET',
  dataType:'html',
  success:function(content){
   $('#ajax-html').html(content);
  }
 });
});

This will produce the same result. I recommand you to use this method whenever you want to make an AJAX call to the sever, because it is more flexible and you will have more control!

6 Animating the UI

When it comes to animation, jQuery also allows Web designers to simply animate the DOM elements. jQuery has the animate() method that create animation effects on various CSS properties. See the following example:

1
2
3
4
5
6
7
8
9
10
11
12
$('#start-animation').bind('click', function(){
 $('.red-square').animate({
  "margin-left": 400,
  "padding": 100
 } );
});
$('#reset-animation').bind('click', function(){
 $('.red-square').animate({
  "padding": 0,
  "margin-left": 0
 } );
});

Feel free to read the documentation page about the animate() method if you are curious about making more advanced animation. However, if you are looking to add more widgets and effects to your UI, the User Interface for jQuery is here to help you.

7 Demo

To see all of these examples in action, please head up to the demo page.

Enjoy with jQuery :)


In the same category
 ♥ 




Scan this with your mobile to visit http://cheghamwassim.com/blog/playing-with-jquery