jQuery Event Handling: Binding and Unbinding

Video tutorial to demonstrate binding and unbinding of events in jQuery.

Events are objects which has data and methods in it.

In this tutorial we are taking 3 paragraph tags with some text inside it.
Once the user clicks on a paragraph, we display the string in the paragraph in an alert box.

Strings in our example are:
Apple
Oracle
Microsoft

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
 <head><title>Bind & Unbind of Events: jQuery!</title></head>
 <body>
                      <p>Apple</p>
                      <p>Oracle</p>
                      <p>Microsoft</p>
 
                      <button>Unbind</button>
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we’re taking 3 paragraphs with some string in it.
And a button, to unbind the events associated with those paragraph texts!

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
  $("p").bind( 'click', function() {
    alert( $(this).text()  );
  });
 
  $("button").bind( 'click', function() {
    $("p").unbind();
  });
 
});

Here p tag is associated with click event. So once the user clicks on the p tag, an alert box appears with the text present inside the paragraph which was being clicked.
button is also associated with click event. So once the user clicks on the button, all the events (click event in our example ) associated with the p tag gets removed, detached, unbinded.

We could also write the code in usual way: i.e., in convenience method as shown below

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
  $("p").click( function() {
    alert( $(this).text()  );
  });
 
  $("button").click( function() {
    $("p").unbind();
  });
 
});

This code does the same thing as shown in binding method above.
Check with both the codes while you try it on your own.

Video Tutorial: jQuery Event Handling: Binding and Unbinding


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=Q4EKDkBOuXU [Watch the Video In Full Screen.]



Binding and Unbinding of events would be helpful when we develop applications which does require all the or some events to be detached after some task is completed.

Also try other events like:
.dbclick()
.focus()
.focusin()
.focusout()
.hover()
.keypress
.keyup
.keydown
.mouseover()
.mouserin()
.mouseout()
.submit()
.select()
.scroll()
.trigger()
.toggle()
.load()
.unload() ..etc

Animate Image with ‘this’ Selector: jQuery

This video tutorial illustrates the use of ‘this’ selector in jQuery.

The $(this) selector gives us an easy way to point to the current element.

In this video tutorial, we take 4 images in our html document. Upon clicking the image, the clicked image fades out of the document.
Once the restore button is clicked, all the images fade in again.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
 <head><title>this selector in jQuery!</title>
 <style type="text/css">
  img {
   padding: 10px;
  }
 </style>
 </head>
 <body>
                     <img src="images/aperture.png" width="79" height="79" />
                     <img src="images/coda.png" width="79" height="79" />
                     <img src="images/finder.png" width="79" height="79" />
                     <img src="images/safari.png" width="79" height="79" />
                                    <br />
                     <button id="restore">Restore Images</button> 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we take:
4 images.
Link to jQuery library.
Link to our custom javascript file my_script.js

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
 $("img").click( function() {
   $(this).fadeOut();
 });
 
 $("#restore").click( function() {
   $("img").fadeIn();
 }); 
 
});

Here, we track the image being clicked and with the help of this selector select that particular image and apply fadeOut effect to it.
Once the restore button is clicked, we select all the img tags and restore all the images with fadeIn effect.

Video Tutorial: ‘this’ Selector in jQuery


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=p-lksl7KSdg [Watch the Video In Full Screen.]



We could take id for each image and then apply fadeOut effect on that image. But this would create overhead in the code and memory and the code maintainability in larger application development.
So having this selector in our tool box helps us be a better developer.

Variables and Javascript Methods In jQuery

In this video tutorial we shall see how to use variables and javascript methods in jQuery.

In this tutorial, we shall take a image inside our html document. Once the user clicks on this image, we shall use some javascript methods to generate random discounts and display it using alert box.

Note:
var is a keyword to declare variable.
Math.random() generates random numbers between 0 and 1.
Math.floor() is used to round off the floating point number to integer.
alert() is used to show the message stored in the variable in alert box.
+ is concatenation operator.

HTML code
index.html

1
2
3
4
5
6
7
8
9
<html>
 <head><title>Variables and JavaScript Methods: jQuery</title></head>
 <body>
                      <img src="images/aperture.png" width="79" height="79" />
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we are including 1 image.
We have also linked the web page to jQuery library file and our my_script.js file.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
 $(document).ready( function() {
 
   $("img").click( function() {
 
     var discount = Math.floor( Math.random() * 5 ) + 10;
     var msg      = "Discount: "+discount+"%";
     alert(msg);
 
   });
 
 });

Once the web page is loaded, and the user clicks on the image:
Math.random() function generates some random number between 0 and 1, which is multiplied by 5 and the resulting number is then rounded off to a integer number using Math.floor() method.
This number is then added with some string message and is stored inside another variable called msg.
This is passed to alert() method and is displayed on a alert box.

Math.random() and Math.floor() and alert() are javascript functions.

Video Tutorial: Variables and Javascript Methods In jQuery


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=IfGmVi3ZuVw [Watch the Video In Full Screen.]



If you want to learn “javascript” visit Javascript Category on our blog.

With this tutorial, you now know that, your javascript knowledge will come handy. If you don’t know Javascript, still you need not worry as we would explain the things we will use in our jQuery tutorial.

Append/Add and Remove HTML/XML Elements: jQuery

Video tutorial to illustrate adding or appending an html element or removing an html element from the web page using jQuery: DOM (Document Object Model)

jQuery uses: .append(); and .remove(); functions to accomplish this task.

We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.

In this example, we are illustrating with the help of an ordered list, by adding and removing its list items.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
 <head><title>Add/Append and Remove Elements!</title></head>
 <body>
            <ol>
             <li></li>
             <li></li>
            </ol>
 
 
          <button id="add_li">Add List</button>
          <button id="remove_li">Remove List</button>
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we have two list items and two buttons.
Buttons have unique id’s: add_li, remove_li Clicking on which the list items get added and removed respectively.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
 $("#add_li").click( function() {
    $("ol").append("<li></li>");
 });
 
  $("#remove_li").click( function() {
    $("li:last").remove();
 });
 
});

Once the document is loaded and the user clicks on Add List button, the list item gets added.
Once the document is loaded and the user clicks on Remove List button, the list item gets deleted.

1
    $("ol").append("<li></li>");

Here li tag gets appended to ol tag.

1
    $("li:last").remove();

First select the element to be removed, and then call remove() method.
Here, we select the last list item in the ordered list and then invoke remove method, which removes li one at a time in reverse order.

Video Tutorial: Append/Add and Remove HTML Elements: jQuery


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=jexv6AfI2lE [Watch the Video In Full Screen.]



If we select li and apply remove() method on it, it would remove all the list items from the document. So we need to specify the list item to be removed. In our case, we are interested in removing the last list item from the ordered list.

1
    $("li").remove();

Using append() and remove() methods, try to append and remove string and other html and xml elements from the document.
You could do the same on XML documents too.

Also Learn:
XML Tutorials

Descendant Selectors: jQuery

Video tutorial illustrating the syntax of Descendant selectors.

For the purpose of demonstration, we are using simple html structure. It may not suit the requirement of a descendant selector, but we’re using it to keep things simple and easy to understand the syntax of descendant selectors.

In a complex xHTML or XML structure we could have multiple p tags nested inside a div tag and you want one of these p tags to work on. In such a complex case, you are better to go with descendant selectors.

You could select it as follows:

1
 $("div p:first")

Here it selects the first p tag present inside the div.

jQuery uses simple verbs like first, append, remove etc: which we’ll cover in upcoming tutorials.

Video Tutorial: Descendant Selectors: jQuery


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=t044xeB1wKQ [Watch the Video In Full Screen.]



xHTML code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
 <head><title>Descendant Selectors</title>
 
 <link rel="stylesheet" href="style.css" type="text/css" />
 
 </head>
 <body>
 
   <div id="main">
 
    <div>
 
     <p>Technotip IT Solutions</p>
 
    </div>
 
   </div>
 
   <button id="main_div">Main Div</button>
   <button id="sub_div">Sub Div</button>
   <button id="sub_div_para">Sub Div Paragraph</button>
 
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

In the xHTML file, observe the nesting of elements / tags. And the id’s given to div and the buttons.

jQuery Code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready( function() {
 
 $("#main_div").click( function() {
   $("#main").css("background-color", "black");
  });
 
  $("#sub_div").click( function() {
   $("div div").css("background-color", "yellow");
  });
 
    $("#sub_div_para").click( function() {
   $("div div p").css("color", "orange");
  });
 
});

To know about .css method of jQuery watch: Animation of Text and Image: jQuery

Observe the descendant selectors in above code.

To select a div inside another div, we write:

1
$("div div")

To select a p tag inside a div which is inturn inside another div, we write:

1
$("div div p")

We could even combine the id, class names and the tag names while selecting the elements.
class name: para

1
$("div div p.para")

ID name: para

1
$("div div p#para")

Optimization Tip:
Being as specific as possible helps speedup the process of selecting the element.

Optimize / Improve Performance of jQuery Applications

Video tutorial illustrating simple tweaks which help optimize / improve the performance of jQuery Applications.

To Optimize
1. Write all javascript programs in an external file and embed it into the html pages.
2. Whenever possible, embed the javascript file at the end of body tag. i.e., just before the closing body tag.
3. It’s also good practice to separate CSS coding to an external file and then embed it to the web pages.

How it helps ?
1. i. If you have thousands of web pages, writing the same code on all the pages and maintaining it and/or modifying it is a touch job.
Having it in an external file helps in re-usability and maintainability.
ii. It only loads the javascript files once and do not load the same files again and again for all other pages, hence saving a lot of bandwidth. Also highly optimizing the load time of web pages.
2. When the parser encounters these javascript files, they stop loading all other elements and allocate all its bandwidth to load javascript file. So writing it at the end of body tag helps. Since all other important elements like images, content will be loaded before these time-consuming javascript files.

Video Tutorial: Optimize / Improve Performance of jQuery Applications


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=BsPgkr-YGMs [Watch the Video In Full Screen.]



Above video uses Animation of Text and Image: jQuery code to illustrate the optimization concept. If you have not already seen the video, we highly encourage you to watch it and practice it.

In our future tutorials we will be writing most of our javascript code in external file and will be embedding them at the end of body tag. With this tutorial you know why we would do that!

Animation of Text and Image: jQuery

Video tutorial to illustrate animation of text and image using jQuery.

In this tutorial, we accomplish:
Animation of text: using animate method.
Display of hidden image: using fadeIn method.
Toggle of image: using slideToggle method.
Change the color of the text being animated: using jQuery’s css method.

xHTML code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
 <head><title>jQuery Basics</title>
 </head>
 <body>         <button id="top">Move Top</button>
                <button id="down">Move Down</button>
                <button id="blue">Blue Coloring!</button>                
                <button id="img_show">Show Image</button>
 
               <div id="move">jQuery is awesome!</div>
               <img src="http://technotip.com/logo.png"/>
 
 
 </body>
</html>

Here we have 4 buttons, 1 div tag which contains some string in it, and 1 image tag.
Each button has its own unique ID, which is referenced to track user click event.

CSS code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  <style type="text/css">
    #move{
      position: absolute;
      top: 200;
      left: 400;
    }
    img {
      display: none;
      padding: 10px;
      position: absolute;
      top: 100;
      left: 400;
 
    }
  </style>

Using Cascading Stylesheet we position the string present in div tag and the image conveniently on our web page.

jQuery
Move Top

1
2
3
4
5
6
7
$(document).ready( function() {
 
    $("#top").click( function() {
       $("#move").animate({top: 30}, 200);
     });
 
});

Once the #top button is clicked, the string inside div tag(which has move as its id), moves upwards leaving 30px from top of the document and 200px from left.

Move Down

1
2
3
4
5
6
7
$(document).ready( function() {
 
    $("#down").click( function() {
       $("#move").animate({top: 200}, 200);
     });  
 
});

Once the #down button is clicked, the string inside div tag(which has move as its id), moves down leaving 200px from top of the document and 200px from left.

Changing CSS property/value using jQuery

1
2
3
4
5
6
7
$(document).ready( function() {
 
 $("#blue").click( function() {
        $("#move").css("color", "blue");
     });
 
});

Once the #blue button is clicked, the color of string inside div tag(which has move as its id), changes to blue.
.css() method takes 2 parameters, first one being css property and the second one its value.

Toggle image with sliding effect

1
2
3
4
5
6
7
$(document).ready( function() {
 
   $("#img_show").click( function() {
       $("img").slideToggle("slow");
     });
 
});

Once the #img_show button is clicked, the image slides and toggles with slideIn and slideOut effect.

Image appears on the web page with fadeIn effect

1
2
3
4
5
6
7
$(document).ready( function() {
 
   $("#img_show").click( function() {
       $("img").fadeIn("slow");
     });
 
});

Once the #img_show button is clicked, the hidden image fades into the web page.
The image is hidden with the help of css.

Video Tutorial: Animation of Text and Image: jQuery


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=1nDGjCrfvrU [Watch the Video In Full Screen.]



Full code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<html>
 <head><title>jQuery Basics</title>
 
  <script src="script/jquery-1.8.1.min.js"></script>
  <script type="text/javascript">
 
   $(document).ready( function() {
 
 
     $("#top").click( function() {
       $("#move").animate({top: 30}, 200);
     });
 
     $("#down").click( function() {
       $("#move").animate({top: 200}, 200);
     });     
 
     $("#img_show").click( function() {
       $("img").slideToggle("slow");
     });
 
     $("#blue").click( function() {
        $("#move").css("color", "blue");
     });
 
     $("#txt_toggle").click( function() {
        $("#move").slideToggle("slow");
     });
 
   });
 
  </script>
 
  <style type="text/css">
    #move{
      position: absolute;
      top: 200;
      left: 400;
    }
    img {
      display: none;
      padding: 10px;
      position: absolute;
      top: 100;
      left: 400;
 
    }
  </style>
 
 </head>
 <body>         <button id="top">Move Top</button>
                <button id="down">Move Down</button>
                <button id="txt_toggle">Text Toggle</button>
                <button id="blue">Blue Coloring!</button>                
                <button id="img_show">Show Image</button>
 
               <div id="move">jQuery is awesome!</div>
               <img src="http://technotip.com/logo.png"/>
 
 
 </body>
</html>

Watch previous day videos and you’ll understand today’s and forthcoming video tutorials easily.

Previous Day Videos:
jQuery Basics: Replace Text/String Inside HTML Document
jQuery: Selectors, Methods, Effects
jQuery: Basic Image Effects

jQuery: Basic Image Effects

Video tutorial illustrates the fadeToggle, fadeIn, fadeOut effect on image using jQuery.

jQuery Code

1
2
3
4
5
6
7
8
9
10
11
 <script type="text/javascript">
               $(document).ready( function() {
 
                 $("#togg").click( function() {
 
                   $("img").fadeToggle("slow");
 
                 });
 
               });
  </script>

Once the document is ready and the user clicks on the button(with togg as its id), the image fades In and fades Out.
This fadeIn and fadeOut effect is accomplished using fadeToggle method of jQuery.

To understand the basic coding of jQuery, please watch previous day videos about selectors and methods.

Complete Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<html>
 <head><title>Image Toggle</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
  </script>
  <style type="text/css">
   img{
    position: absolute;
    top: 100;
    left: 200;
   }
  </style>
 
  <script type="text/javascript">
               $(document).ready( function() {
 
                 $("#togg").click( function() {
 
                   $("img").fadeToggle("slow");
 
                 });
 
               });
  </script>
  </head>
 <body>
  <img src="http://technotip.com/logo.png" />
  <button id="togg">Toggle Image!</button>
 </body>     
</html>

Inside the HTML document we have added a image and a button. Once the user clicks on this button, our jQuery code gets executed and the fade In and fade Out effect is presented to the user.
For the jQuery code to be interpreted by the javascript interpreter, we need to include the jQuery standard library file to our web page.

Some basic CSS makes the image look well positioned.

Video Tutorial: jQuery: Basic Image Effects


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=CQUeZ7WcOgM [Watch the Video In Full Screen.]



Practice this image effect program and also try using
.fadeIn();
.fadeOut();

.slideIn();
.slideOut();
.slideToggle();

functions instead of .fadeToggle(); function.

Also notice that, page doesn’t reload while you perform these DOM manipulations using jQuery. This is a major advantage which builds up rich user experience.

jQuery: Selectors, Methods, Effects

This video tutorial shows the basics of jQuery Selectors, Methods and some nice little image and text effects.

It’ll be fun..

Note:
$(); is a shortcut to $jQuery(); and it’s called Selector.
Its used to select id’s, class, elements.

Selecting id’s, classes and elements is similar to that of CSS Selectors.
For id use # symbol.
For Class use . symbol.
For tags or elements, use tag name or element name.

jQuery Example Code:

1
2
3
4
5
 $(document).ready( function() {
    $("p").click( function() {
      $("img").fadeOut("slow");
  });
});

Once the document is ready or loaded and the user clicks on paragraph text, the image slowly fades out. Simple.

Video Tutorial: jQuery: Selectors, Methods, Effects


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=G-bYNbZuzzE [Watch the Video In Full Screen.]



Other methods / effects to try ..

.slideUp();
.slideDown();
.slideToggle();

.fadeIn();
.fadeOut();
.fadeTo();
.fadeToggle();

$(“p”).hide(“fast”);
$(“p”).show(“slow”);
$(“img”).slideUp();
$(“p”).html(“Replacement String”);

We’ll come up with some more video tutorial ..stay subscribed, and try these fun program yourselves too.

Also share how you’re using jQuery in your projects and what you actually want to accomplish using it.

Sign into our forum and start discussing various jQuery and other topics and share your ideas and learn more collectively.

If you were not able to execute the above program, then need not worry, just search on our blog and you’ll find full detailed video tutorial writing and executing it step-by-step.
Hope you’re enjoying it.

jQuery Basics: Replace Text/String Inside HTML Document

Today lets start with learning jQuery.

In this video we show you where to get the jQuery library file and the text editor we are using to write our jQuery programs.

Since we are on Windows 7, we choose pspad.

For all the links and installation procedures, please watch the short video below.

To start the day 1 of learning jQuery, let’s do a simple string replacement program.
We shall change the text inside p tag once the user clicks on the text inside p tag.

Complete Code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
 <head><title>jQuery Basics</title>
 
  <script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(document).ready( function() {
      $("p").click( function(){
 
          $("p").html("jQuery is awesome!");
 
      } );
    } 
    );
  </script>
 </head>
 <body>
                  <p>JavaScript</p>
 </body>
</html>

First include the jQuery library file..and in next script tag, start writing your jQuery code.
The code is triggered once the html document loads i.e., when it is ready.
Once the page loads, a anonymous function is being called and is ready to register the user events.

When a user clicks on the p tag or its content, the string content(which is a separate node in DOM), is changed to jQuery is awesome!

Video Tutorial: jQuery Basics: Replace Text/String Inside HTML Document


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=z917odQd30w [Watch the Video In Full Screen.]



Write this program and setup your jQuery learning environment and be ready for the future video tutorials.

Try to change the tags, content and the code and also invoke the action for other user events other than just click.