Close modal window when user clicks anywhere outside of modal [closed]

2

I'm using a modal window plugin, but I'm not able to make the modal window close.

JSFiddle example: link

(function($){

  $.modal = function (el, options) {
      this.options = options;
      this.$el = $(el);
      this.$target = $(el.hash || this.$el.attr('data-target'));
      this.$backdrop = $('.modal-backdrop');

      if (this.$target.length) {
        this.$el.data("modal", this);
        this.init();
      }
    };  


  $.modal.prototype = {

    init: function() {
      var self = this,
          settings,
          backdrop = $('<div/>').addClass('modal-backdrop fade');

      if (!self.$backdrop.length) {
        self.$backdrop = backdrop.appendTo('body');
      }

      self.settings = settings = $.extend({}, self.defaults, self.options);

      self.$target.on('', function(e) { self.hide(e) });
      self.$el.on('click', function(e) { self.show(e) }); 
    },

    toggle: function(e) {
      return (this.$target.hasClass('in')) ? this.hide(e) : this.show(e); 
    },

    show: function(e) {
      e.preventDefault();
      e.stopPropagation();
      this.$target.addClass('in');
      this.$backdrop.addClass('in');
      $('body').addClass('modal-open');
    },

    hide: function(e) {
      e.preventDefault();
      e.stopPropagation();

      var className = e.target.className;

      if (className == 'modal-dialog' || className == 'close') {
        this.$target.removeClass('in');
        this.$backdrop.removeClass('in');
        $('body').removeClass('modal-open');
      }
    },

    defaults: {

    }

  };

  $.fn.modal = function(options) {
    return this.each(function() {
      new $.modal(this, options);
    });
  };  

  // self-instantiate on elements with
  // data-toggle='popover'
  $(document).ready(function() {
    $('[data-toggle=modal]').modal();
  });
}(jQuery));

/*
* Close
*/

jQuery('.modal-dialog').click(function () {
    var id = jQuery(this).attr('id').replace('_backgroundElement', '');
    $find(id).hide();
});
    
asked by anonymous 05.06.2017 / 02:20

1 answer

2

The code is correct, only missing is to assign the event you want to run, which in this case is the "click".

Change line 29 of your code in the fiddle of:

self.$target.on('', function(e) { self.hide(e) });

To:

self.$target.on('click', function(e) { self.hide(e) });

I updated your code and it worked:

link

    
05.06.2017 / 02:32