I have a jquery plugin that uses popular plugin pattern. The plugin opens a modal window and the modal window can also be closed. I also want to add some more functionality like, closing the window by pressing the escape key or closing the window by clicking outside the modal. How do I integrate this new code into the plugin?
NOTE: Also note that event handlers are attached to the body and document containers which is present outside the Modal window created using the plugin. I’m aware that in order to add stuff to the plugin I can attach methods to Plugin.prototype.xxx. Will I be able to do the same here or we should handle this case differently?
//press 'Esc' key - hide Modal
$('body').bind('keydown', function(e) {
if (e.keyCode == 27) { // "Esc" Key
if ( $('.show').is(':visible') ) {
$('.Close').click();
}
return false;
}
});
//click outside Modal - hide Modal
$(document).mouseup(function (e){
var container = $(".Window");
if (!container.is(e.target) && container.has(e.target).length === 0){
$('.Close').click();
}
});
Popular plugin pattern I’m using for the plugin:
;(function ( $, window, document, undefined ) {
// Create the defaults once
var pluginName = 'defaultPluginName',
defaults = {
propertyName: "value"
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );
Just add the code in the init method, but be shure you only target the desired elements.