Working With Images: Small jQuery Application

In this video tutorial, we shall test our skills in jQuery: bind, unbind, append and remove functions. Also we shall see the use of chain methods.

jQuery Event Handling: Binding and Unbinding
Animate Image with ‘this’ Selector: jQuery
Append/Add and Remove HTML/XML Elements: jQuery

Assume that a client has mailed her requirements to us:
She has 5 images in her html page.
Once the user clicks on a image, a message should popin beside the image.
Image should be clickable only once.
Once the user clicks on other images, the messages appended beside previously clicked image must be removed.

With these requirements in mind, we shall start developing our image based jQuery Application.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<html>
 <head><title>Working With Images: Small jQuery Application</title>
 <style type="text/css">
 img{
  padding: 10px;
 }
 </style>
 </head>
 <body>
 
   <div> <img src="images/aperture.png" width="69" height="69" /> </div>
   <div> <img src="images/coda.png" width="69" height="69" /> </div>
   <div> <img src="images/finder.png" width="69" height="69" /> </div>
   <div> <img src="images/photoshop.png" width="69" height="69" /> </div>
   <div> <img src="images/safari.png" width="69" height="69" /> </div>
 
   <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 included 5 images and have added 10px padding using CSS.
Each image is being placed inside a div tag.

Note:
So img is a child of div or div is the parent of img.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
$(document).ready( function() {
 
  $("img").click( function() {
   $("b").remove();
   $(this).parent().append("<b>You clicked on Me!</b>");
   $(this).unbind();
 });
 
});

Once the document is ready and the user clicks on a image:
1. Any b tag present in the document is removed. Thus, the message associated with the image which was being clicked previously is removed.
2. The parent tag of the image being clicked: i.e., div tag is selected and a message with b tag is appended to it, which appears beside the image being clicked by the user.
3. The event associated with the image being clicked is removed.

Note:
Use of function().function() is called chain method.
Example:
parent().append();
next().parent().remove(); etc

Make sure to maintain the order of the code. If you replace or rearrange the code in a way other than above, you wouldn’t get expected result.
While practicing, change the order of the code and look for the output, that would help you understand the code and the flow / execution flow well.

Video Tutorial: Working With Images: Small jQuery Application


[youtube https://www.youtube.com/watch?v=MckRCdhiZBI]

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



Keep testing your jQuery skills by doing some mini projects like this one.
Let it be small, so that it doesn’t take forever to test your skills.

You could even test and enhance your jQuery skills by helping people on our forum.

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


[youtube https://www.youtube.com/watch?v=Q4EKDkBOuXU]

YouTube Link: https://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


[youtube https://www.youtube.com/watch?v=p-lksl7KSdg]

YouTube Link: https://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


[youtube https://www.youtube.com/watch?v=IfGmVi3ZuVw]

YouTube Link: https://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


[youtube https://www.youtube.com/watch?v=jexv6AfI2lE]

YouTube Link: https://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