Easy fading using jQuery
Whilst working on a project recently I came across a need for us to show a selection of images depending on their type and when a link to them is clicked.
I decided to use jQuery as it saves a lot of time as most of the work is done for you.
I will step through the code so you can see how I did it.
As with any jQuery, we are required to use the following line to tell our jQuery code to run as soon as DOM is ready rather than when the page has finished loading.
$(document).ready(function(){
The next line detects any click from a link inside the div with an id of “links”
$('#links a').click(function(){
Once a link has been clicked any attribute from that link is accessible through $(this), so the next line sets up a new variable called “color” and takes the “rel” attribute from the tag and puts it into our new variable.
var color = $(this).attr('rel');
Once we know which colour link has been clicked we can then fade out all images that have a different colour and fade in the colour that has been clicked.
$('#tiles div.tile:not(.' + color + ') img').fadeTo("slow", 0.3);
$('#tiles div.' + color + ' img').fadeTo("slow", 1);
To finish off we need to close our function brackets. You will notice there is a “return false;”. This is to stop the link actually activating the href attribute and basically overriding it so we can do our magic. This becomes useful when users don’t have Javascript activated in there browser, you can make the link work as normal. Unfortunately, you would need to create separate pages with different colours highlighted instead. (sigh!)
So, to sum up I have put all the code below and you will need to remember to include the latest jQuery Javascript file from www.jquery.com
All the HTML you can grab from the source of the demo page.
$(document).ready(function(){
$('#links a').click(function(){
var color = $(this).attr('rel');
$('#tiles div.tile:not(.' + color + ') img').fadeTo("slow", 0.3);
$('#tiles div.' + color + ' img').fadeTo("slow", 1);
});
return false;
});
Hopefully, this will be useful to someone. Have fun!
August 19th, 2008 at 3:41 am
[...] Easy Fading Using jQueryShow only images of a ceratin selected type with fading. [...]
November 6th, 2008 at 3:17 am
It is beautifully turned out .. I liked ..) would be continuously zahazhivat to you.