I am working on this html5 file uploader plugin but it has a bug which I can’t understand and fix it.
The idea of this plugin is to attach a group of function to a targeted button only when it is clicked.
But When I click on the ‘button-1’ click event, the ‘button-2’ click event has been triggered at the same time when the on change event is happening. I think the change event must have been triggered twice.
You can try to click on the upload button and see what I mean.
Any idea what goes wrong in this plugin?
(function($){
// Attach this new method to jQuery
$.fn.extend({
// This is where you write your plugin's name
upload_file_html5: function(options) {
// Set the default values, use comma to separate the settings, example:
var defaults = {
objectSuperparent: '.media'
}
var options = $.extend(defaults, options);
var o = options;
var $cm = this.click(function(e){
// <a> button is the object in this case.
var object = $(this);
// Get other info from the element belong to this object group.
var object_href = object.attr('href');
var object_parent = object.parent();
alert($cm.selector);
// Trigger the click event on the element.
// Due to security policies triggering click on the input type=file is not allowed/supported in some browsers and Opera is one of them.
//$('input[type=file]').trigger('click'); // or:
$(".upload-file",object_parent).click();
return false;
});
// Trigger ajax post when ever the file is changed by the user.
var $cm_2 = $(".upload-file").change(function(){
// <input> is the object in this case.
var object = $(this);
var object_form = object.parent();
var object_superparent = object.parents(o.objectSuperparent);
var path_config = $($cm.selector,object_superparent).attr('href');
var path_post = object_form.attr('action');
alert($cm.selector);
//alert(path_config);
....
....
});
}
});
})(jQuery);
Check my variant of your code: http://jsfiddle.net/es8Vh/3/
Basic jQuery plugin structure: