So I have a form to submit photos (to a total of 8), and I'm trying to apply a small effect: once you choose a photo, the button hides and the file name is displayed along with a 'X' to remove its selection.
However, when I add multiple photos and try to remove one, the event gets called multiple times, and the more I click, more multiple events are fired, all from the same element.
Can anyone figure it out?
var Upload = {
init: function ( config ) {
this.config = config;
this.bindEvents();
this.counter = 1;
},
/**
* Binds all events triggered by the user.
*/
bindEvents: function () {
this.config.photoContainer.children('li').children('input[name=images]').off();
this.config.photoContainer.children('li').children('input[name=images]').on("change", this.photoAdded);
this.config.photoContainer.children('li').children('p').children('a.removePhoto').on('click', this.removePhoto);
},
/**
* Called when a new photo is selected in the input.
*/
photoAdded: function ( evt ) {
var self = Upload,
file = this.files[0];
$(this).hide();
$(this).parent().append('<p class="photo" style="background-color: gray; color: white;">' + file.name + ' <a class="removePhoto" style="color: red;" href="#">X</a></p>');
if(self.counter < 8) { // Adds another button if needed.
Upload.config.photoContainer.append( '<li><input type="file" name="images"></li>');
self.counter++;
}
Upload.bindEvents();
},
/**
* Removes the <li> from the list.
*/
removePhoto: function ( evt ) {
var self = Upload;
evt.preventDefault();
$(this).off();
$(this).parent().parent().remove();
if(self.counter == 8) { // Adds a new input, if necessary.
Upload.config.photoContainer.append( '<li><input type="file" name="images"></li>');
}
self.counter--;
Upload.bindEvents();
}
}
Upload.init({
photoContainer: $('ul#photo-upload')
});
bindEvents
method your'e binding events not to the one element, which needs to be changed, but to all elements. Maybe that causes an issue.