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


 this selector in jQuery!
 
 
 
                     
                     
                     
                     
                                    

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

jQuery code
my_script.js

$(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 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.

View Comments