I'm trying to replace an image using for loop. The main div has 7 images where only one image is visible, due to the height of the div, I'm also using overflow auto. The for loop works once and change the image. The image with id 1 disappears and next one, id 2, appears as I move the mouse to the right. The loop will work only once and it won't work again. I have even printed the pageX pageY to see if it works, but that freezes. I know the problem is with when I try append() the new image. Please see code below.
$.ajax({
type: "GET",
url: "xml/pdf_xml.xml",
dataType: "xml",
success: function(xml) {
var items = parseXml_img(xml);
load_img(items);
img_scroller(items);
}
});
function parseXml_img(xml) {
var items = [];
$(xml).find("Image").each(function(idx, v) {
items.push({
title: $(this).find("Title").text(),
date: $(this).find("Date").text(),
id: $(this).find("id").text(),
});
});
return items;}
function load_img(items) {
var id =1;
for (var i = 0; i < items.length; i++) {
items[i].id= id++;
var galleryImage = "<div id=\"currDiv-"+items[i].id+"\"><img src=\"img/"+items[i].title+"\" id=\"curr-"+items[i].id+"\" class=\"currId\"/></div>";
$('#main-image').append(galleryImage);
//$('#main-image').children().not("[id='curr-1']").hide();
}
}
function img_scroller(items) {
var newId;
var xPrev = 0;
var currentId;
var idLength = items.length;
$('.currId').mousemove(function(e) {
var newId; var xPrev = 0; var currentId;
var idLength = items.length;
var str =$(this).attr('id');
var ret = str.split("-");
var str1 = ret[0];
var str2 = ret[1];
currentId = str2;
var newImg ="";
if(xPrev<e.pageX) {
newId=0;
$('#test').html('right,'+e.pageX+','+e.pageY);
//currentId++;
newId = currentId;
if(newId >= idLength){
newId=idLength;
}
//var leftId = newId;
// var rightId = newId;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var j = newId;
$('#main-image').children().html("");
for (j; j < items.length; j++) {
newImg = "<img src=\"img/"+items[j].title+"\" id=\"curr-"+items[j].id+"\" class=\"currId\"/>";
$('#currDiv-'+items[j].id).html(newImg);
}
} else if(xPrev>e.pageX)
{
$('#test').html('left,'+e.pageX+','+e.pageY);
}
xPrev=e.pageX;
});
}
I've made a change at the img_scroller, please below
if(xPrev<e.pageX) { newId=0; newId = currentId; if(newId >= idLength){ newId=idLength; } var j = newId+1; items=[]; var testt=''; for (j; j < items.length; j++) { testt=items[j].id; $("img[id='"+items[j].id+"']").show(); $('#test').html(testt); } return testt; $('#test').html(testt); }
What I've changed shown above:
I've created a few divs to go below the images, so I could always get the scrollbar. I'm trying to show and hide the images as they go on the loop. But it seems that the loop is not reading the items array.