0

I am having some issue with document.on('click') event, The first time I open the form it binds the 'click' event to the document but it does not execute it which is what I expect. But when I close the form and try to open it again, The document binds the 'click' event and executes it right away. I was wondering if there is any way to solve this issue. Right now I am using the setTimeout(...) function as a hacky way to solve this issue but I am looking for a better way to fix it.

initXXXXForm = function() {
  var $form = $('.zzzz'),
      $formOpen = $('.xxxx'),
      $formClose = $( '.yyyy' ),
      $formMask = $('.wwww'),
      toggleForm = function() {
        if ($form.hasClass('active') === true) {
          // close form
          $form.removeClass('active');
          $formMask.removeClass('active');
          $(document).off('click'); // remove event on document to close form
        }
        else {
          // open form
          $form.addClass('active');
          $formMask.addClass('active');

          // bind close event when clicking outside form, set short timeout so this click event doesn't interfere with others
          setTimeout(function() {
            $(document).on('click', function(e) {
              if ($(e.target).closest('.xxxx-form').length === 0 ) {
                $(this).off('click');
                toggleForm();
              }
            });
          }, 100);
        }
      };

  $formOpen.on('click', function() {
    toggleForm();
  });

}
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Arar
  • 1,926
  • 5
  • 29
  • 47
  • It is wrapped inside iffy (function( $ ) { ... })( jQuery ); – Arar Mar 18 '16 at 16:27
  • Have you seen solutions similar to: http://stackoverflow.com/questions/6140278/how-to-close-hide-div-clicking-outside-of-it-but-not-inside ? – Roko C. Buljan Mar 18 '16 at 16:29
  • What does opening the form mean here? – SpoonMeiser Mar 18 '16 at 16:29
  • What do you want: the clicking outside the form should close the form? – skobaljic Mar 18 '16 at 16:31
  • the clicking outside the form closes it but I was wondering if there is away to get rid of this timeout function !! – Arar Mar 18 '16 at 18:24
  • @RokoC.Buljan This approach $formOpen.hover(function(){ notHov^=1; }); // Toggle flag on hover works fine, But i would guess that the timeout is actually more efficient. hover and timeout solutions are a work around solutions. I am trying to understand the root cause of the issue – Arar Mar 18 '16 at 20:40

1 Answers1

0

How about you change that last statement to this:

$formOpen.off("click", toggleForm).on("click", toggleForm);
Hari Lubovac
  • 622
  • 4
  • 14