Close modal window when user click anywhere outside modal

Asked

Viewed 722 times

2

I’m using a plugin from a modal window, but I’m not getting the modal window to close.

Example of Jsfiddle: https://jsfiddle.net/2kag95en/

(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();
});

1 answer

2


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

Change line 29 of your code in the fiddle:

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:

https://jsfiddle.net/2kag95en/1/

  • After making this change in the click, the buttons stop working. What should I do to fix?

  • Remove line 48 and 49, e.preventDefault() and e.stopPropagation() - https://jsfiddle.net/2kag95en/3/

  • 1

    Perfect guy! Helped out so much here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.