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]
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.
good