I’m making a picture preview of a link typed in a text box. jQuery is used to send back in a preview <div> the pictures. When multiple pictures, i’m trying to make a navigation to select the picture you want with left right keys.
So i’m adding events to document to capture keys typed. This is done in the success of my ajax request (because it’s async).
My problem is that when the first request is done everything is ok. After the first time, event is fired 2 times, then 3 times; one additional time after each request.
I tried to unbind but it has no effect.
Code:
$.ajax ({
type: "POST",
url: "curl.php",
data: {"lien" : lien},
async: true,
success: function(data) {
console.log(data);
$("#result").html("");
if(data && data != ""){
var images = jQuery.parseJSON(data);
$("#result").html("<img src='"+images[0].nom+"' />");
console.log("Nombre d'images : "+images.length);
if(nav){
$(document).unbind('keydown');
console.log('détruit');
}
function nav() {
$(document).bind('keydown', function(e){
switch(e.which)
{case 37:
if(imagePosition>0){imagePosition--;}else{imagePosition = 0;};
console.log(imagePosition);
$("#result").html("<img src='"+images[imagePosition].nom+"' />");
return false;
break;
case 39:
if(imagePosition<(images.length-1)){imagePosition++;}else{imagePosition = (images.length-1) };
console.log(imagePosition);
$("#result").html("<img src='"+images[imagePosition].nom+"' />");
return false;
break;
}
});
}//fin de nav
nav();
}
}
})
imagePositionis the number to select the picture in the returned array.imageis the array with links of the picture gathered.nav()is the fonction that attach the event to the document
Instead of this
please try and use
Though this is not the ideal way, this will gurantee that before you attach a handler to an event on an element, the other handlers for the same event are removed.