Reputation: 2462
I have a small script here to switch between 2 images... It works like if you select 1st it stay selected, if you select 2nd - 1st one is fading out and 2nd is being selected... Simple like that.
$(document).ready(function () {
$(".theImage img").click(function () {
var a = $(this).parent().attr("id") == "product-holder1" ? "product-holder2" : "product-holder1";
console.log(a);
$(this).fadeOut();
$("#" + a + " img").fadeIn()
})
})
My problem is that I don't know how do I use it for more then 2 images? Let's say I have id "product-holder3" and maybe "product-holder4" so how do I write this in that jquery code, so it still switch between which one is being selected?
HTML:
<div id="product-holder1" class="theImage">
<img src="img/10-normal.png" />
</div>
<div id="product-holder2" class="theImage">
<img src="img/25-normal.png" />
</div>
<div id="product-holder3" class="theImage">
<img src="img/50-normal.png" />
</div>
CSS
#product-holder1 {
background: url("img/10-selected.png");
background-repeat: no-repeat;
height: 182px;
width: 195px;
position: absolute;
top: 40px;
left: 62px;
cursor: pointer;
}
#product-holder2 {
background: url("img/25-selected.png");
background-repeat: no-repeat;
height: 182px;
width: 195px;
position: absolute;
top: 40px;
left: 124px;
cursor: pointer;
}
#product-holder3 {
background: url("img/50-selected.png");
background-repeat: no-repeat;
height: 182px;
width: 195px;
position: absolute;
top: 40px;
left: 186x;
cursor: pointer;
}
Just please tell me how to use it for product-holder3 and maybe one day I need for more images, so please let me know how that works? Thanks a lot!
P.S I don't know anything about jQuery :D
Upvotes: 0
Views: 1104
Reputation: 268324
This is an update based upon discussion in the comments below:
// Listen for the click event of our many containers
$(".theImage").on("click", function(){
// In the event clicked, find image, fade slowly to .01 opacity
$(this).find("img").fadeTo("slow",0).end()
// Then, of siblings, find all images and fade slowly to 100% opacity
.siblings().find("img").fadeTo("slow",1);
});
Demo: http://jsfiddle.net/yvM8Z/2/
Upvotes: 1
Reputation: 976
You need to create a collection that contains the container div's you are cycling through (or at least their ids'). Something like $(".theImage img:parent")
if you don't need to worry about manipulating the cycling order. Then in your click function you can look up the current collection element using the id from $(this).parent().attr("id")
and then get it's index. Once you know the index you can move to the next item in the collection (or wrap to the beginning if you're at the end) and get the new id, setting that as the value of your variable a
.
Upvotes: 0