Reputation: 75
I must start with I am quite a javascript novice.
Currently I am making a website where a whole bunch of items are listed. Each item has a default image and 3 images of different angles of the product. I am using JQuery to show a full sized image over the default when the user hovers over the thumbnail.
My question, I have about 90 items. Is there an easier way to do this only in javascript, without having to nest 90 items.
It must be only HTML / CSS / Javascript
Currently for 3 items it would like this :
$(document).ready(function(){
// First thumbnail on each item
$("#thumb1-1,#thumb2-1,#thumb3-1").hover(function(){
$("#image1-1,#image2-1,#image3-1").show();$("#default1,#default2,#default3").hide();
},function(){
$("#image1-1,#image2-1,#image3-1").hide();$("#default1,#default2,#default3").show();
});
// Second thumbnail on each item
$("#thumb1-2,#thumb2-2,#thumb3-2").hover(function(){
$("#image1-2,#image2-2,#image3-2").show();$("#default1,#default2,#default3").hide();
},function(){
$("#image1-2,#image2-2,#image3-2").hide();$("#default1,#default2,#default3").show();
});
// Third thumbnail on each item
$("#thumb1-3,#thumb2-3,#thumb3-3").hover(function(){
$("#image1-3,#image2-3,#image3-3").show();$("#default1,#default2,#default3").hide();
},function(){
$("#image1-3,#image2-3,#image3-3").hide();$("#default1,#default2,#default3").show();
});
});
Rough visual Most likely will load images at the end of the page to reduce lag, also pages will be split up to about 10 on a page
Upvotes: 0
Views: 94
Reputation: 2275
http://jsfiddle.net/8k5L5myo/2/
var totalImageTypeCount = 10;
var defaultImageCount = 1;
var thumbImageCount = 3;
var overlayImageCount = 2;
var wrapper = $(".wrapper");
var defaultTag = '<div class=".defaultTag"> this is default';
var overlayTag = '<div class=".overlayTag"> this is oeverlay';
var thumbTag = '<div class=".thumbTag"> this is Thumbnail';
var closeTag = "</div>";
for (var a = 0; a < totalImageTypeCount; a++) {
wrapper.append(defaultTag);
for (var b = 0; b < overlayImageCount; b++) {
wrapper.append(overlayTag);
wrapper.append(closeTag);
}
for (var c = 0; c < thumbImageCount; c++) {
wrapper.append(thumbTag);
wrapper.append(closeTag);
}
wrapper.append(closeTag);
}
use for loop to loop through all the image to you need, you can use src=-"dir/yourImage"+a+".jpg"
where a
will loop though 1-max number.
Upvotes: 1
Reputation: 3739
If I understood your situation right, this should work.
$(document).on("mouseenter", "[id^=thumb]", function(e) {
$(this).show();
var itemno = $(this).attr("id").replace("thumb","").replace("/-\d+/","");
$("#default"+itemno).hide();
});
$(document).on("mouseleave", "[id^=thumb]", function(e) {
$(this).hide();
var itemno = $(this).attr("id").replace("thumb","").replace("/-\d+/","");
$("#default"+itemno).show();
});
Upvotes: 0