Mathieu
Mathieu

Reputation: 4787

Factorize javascript/jquery code for hiding modal when click outside

I have a code that work but I don't know how to factorize it. It seems I could be able to do it as they're basically the same code first for desktyop then for touch devices:

//desktop

  $(document).mouseup(function (e)
  {
      var container = $(".messenger");
      if (!container.is(e.target) // if the target of the click isn't the container...
          && container.has(e.target).length === 0) // ... nor a descendant of the container
      {
          container.empty();
          container.off( 'click', clickDocument );
      }
  });



// Touch devices like IPAD and IPHONE we can use following code

$(document).on('touchstart', function (e) {
    var container = $(".messenger");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.empty();
        container.off( 'click', clickDocument );
    }
});

Upvotes: 1

Views: 64

Answers (3)

cFreed
cFreed

Reputation: 4474

Quite easy:

// desktop (mouseup)
// or Touch devices like IPAD and IPHONE we can use following code

  $(document).on('mouseup touchstart', function (e)
  {
      var container = $(".messenger");
      if (!container.is(e.target) // if the target of the click isn't the container...
          && container.has(e.target).length === 0) // ... nor a descendant of the container
      {
          container.empty();
          container.off( 'click', clickDocument );
      }
  });

Upvotes: 2

mottaman85
mottaman85

Reputation: 309

may you can try this:

var eventTouch = function(e){    
    var container = $(".messenger");
        if (!container.is(e.target) 
            && container.has(e.target).length === 0) 
           {
            container.empty();
            container.off( 'click', clickDocument );
           }
    }

$(document).mouseup(eventTouch);
$(document).on('touchstart', eventTouch);

Upvotes: 1

leo.fcx
leo.fcx

Reputation: 6467

Change it to:

var onMouseUp = function (e) {
    var container = $(".messenger");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.empty();
        container.off( 'click', clickDocument );
    }
};

// For Desktop
$(document).mouseup(onMouseUp);

// For devices
$(document).on('touchstart', onMouseUp);

Upvotes: 2

Related Questions