0

I've written script to upload images and for that, I've written a single deleting function which I've called from two functions and whenever I call the deleting function from another function, it triggered at twice.

For Ex:

function getImgTrashEvents(){
  $('.image-demo').bind().click(function(){
    if(confirm("Do you want to delete this image?")){
      //Do something to delete image
    }
  });
}

//Showing images from database
function showPresentImages(){
  //Here I've written ajax call to get all images 
  $.ajax({ 
    url:'get-images', 
    success: function(response){
      //Do something to load UI of images and delete button <img class="image-demo">
      getImgTrashEvents();
    }
  });
}

//Uploading new images
function uploadImages(){
  //demo ajax call to upload photo 
  $.ajax({
    url:'upload-photo',
    success: function(response){ 
      //Load UI with newly uploaded images with class images-demo
      getImgTrashEvents();
    }
  });
}

In this code, I've written 3 functions one is for getting all events of trash image, a second function for showing preset images from database and final function for uploading new images.

Here I am calling getImgTrashEvents(); this function in both functions. But when I call it from both the events from getImgTrashEvents(); are calling twice or more for single click after uploading an image and showing confirm alert twice. And if I call this function in only showPresentImages() function then it's not taking effect for uploadImages().

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • You need to unbind the click event. before binding a new one. `$('.image-demo').unbind("click").click(function(){` – Brahma Dev Sep 30 '17 at 14:51
  • 1
    Why are you adding the click handlers every time you make an AJAX call? If you're trying to add handlers to dynamically-added elements, see https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar Sep 30 '17 at 14:52
  • @Barmar Because it's not taking effect. –  Sep 30 '17 at 14:58
  • If you did proper event delegation it would take effect. – Barmar Sep 30 '17 at 14:59

1 Answers1

2

Not certain if the code is posted to OP correctly at .bind().click()? The issue is the code attaches an additional click event at each call to getImgTrashEvents, showPresentImages, and uploadImages.

Instead you can define the click event outside of getImagTrashEvents, and if necessary call .click() to dispatch the event instead of attaching another event handler to the jQuery object.

$('.image-demo').click(function(){
  if(confirm("Do you want to delete this image?")){
    //Do something to delete image
  }
});

function getImgTrashEvents(){
  $('.image-demo').click()
}
guest271314
  • 1
  • 15
  • 104
  • 177