Reputation: 832
I have three images on a single page and I would like to fade out the elements that aren't clicked on. The script works in the first instance so if you click on one picture, the other two fade. If you think click on an already faded picture, all that happens is that last non-faded picture also fades, instead of it being 100% opacity and the other two faded.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
.opac {
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
border:thick;
}
</style>
<script>
$(document).ready(function(){
$('a.images').click(function()
{
$(this).siblings().stop().animate({opacity: 0.4}, 300);
$('a.images').click(function()
{
$not('this').stop().animate({opacity: 1.0}, 300);
});
});
});
</script>
</head>
html
<body>
<div id="images">
<a class="images" href="#"><img class="click" src="../appalachia.jpg" height="133" /><br/><br/></a>
<a class="images" href="#"><img class="click" src="../appalachia.jpg" height="133" /><br/><br/></a>
<a class="images" href="#"><img class="click" src="../appalachia.jpg" height="133" /><br/><br/></a>
</div>
</body>
</html>
Upvotes: 2
Views: 5349
Reputation: 227240
You are attaching a click
handler inside a click
handler. Every time you click, a new click handler will be added and called on each subsequent click.
Click handlers are called with the newest added called first, which means that last, all the images are set to transparent.
If you want the picture you clicked on to be opaque, and the others transparent, try this:
$('a.images').click(function(){
// Make all images (except this) transparent
$('a.images').not(this).stop().animate({opacity: 0.4}, 300);
// Make this opaque
$(this).stop().animate({opacity: 1.0}, 300);
});
Demo: http://jsfiddle.net/gCsRL/1/
Upvotes: 5
Reputation: 339816
In this code:
$('a.images').click(function() {
$(this).siblings().stop().animate({opacity: 0.4}, 300);
$('a.images').click(function() {
$not('this').stop().animate({opacity: 1.0}, 300);
});
});
you're registering a click handler over and over, for each click. Just try this instead:
$('a.images').click(function() {
$(this).siblings().stop().animate({opacity: 0.4}, 300);
$(this).stop().animate({opacity: 1.0}, 300);
});
Upvotes: 4