2

I've set up a couple of event triggers to close specific elements when the user clicks outside of them. This works great for non-mobile devices, but on a mobile or a tablet they won't fire. I'm assuming this is because tap events trigger differently than clicks. Any suggestions on how to approach this so that a function will cover both aspects?

// Listen for unique event targets
      $(document).on( 'click', function(event) {
        if (!$(event.target).closest( '.modal .content' ).length) {
          $( '.modal' ).fadeOut(200);
        }
        if (!$(event.target).closest( '.language-selector ul' ).length) {
          if ( $( '.language-selector' ).is( ':visible') ) {
            $( '.language-selector >' ).removeClass('active');
          }
        }
        if (!$(event.target).closest( '.searchbox' ).length) {
          if ( $( '.searchfield' ).is( ':visible') ) {
            $( '.searchfield' ).removeClass('active').parents( '.searchbox' ).find( 'input[type="submit"]' ).removeClass( 'active' );
          }
        }
      });
Staffan Estberg
  • 6,795
  • 16
  • 71
  • 107

2 Answers2

2

Yes, click and tap are distinct events.

You can bind both by using JQuery selecter syntax (click tap):

// Listen for unique event targets
      $(document).on( 'click tap', function(event) {
        if (!$(event.target).closest( '.modal .content' ).length) {
          $( '.modal' ).fadeOut(200);
        }
Dave Alperovich
  • 32,320
  • 8
  • 79
  • 101
  • Thanks but I can't get this to trigger except on link targets. Is it because I'm not using jQuery mobile? I would need it to trigger on any element. – Staffan Estberg Jun 09 '15 at 15:47
  • @StaffanEstberg, yes, and no. Mobile with JavaScript is always trial-and-error. JQuery Mobile tries to merge the events, it may be better. Or your issue may be the 300ms differential between tap and click. Considering your fade affect and 200ms differential, it may be. In that case Fastclick may help. Keep trying different solutions until one works. Fast click can be found at https://github.com/ftlabs/fastclick – Dave Alperovich Jun 09 '15 at 16:15
1

Try binding "click" to "touchstart":

$(document).on( 'click touchstart', function(event) {
      if (!$(event.target).closest( '.modal .content' ).length) {
      $( '.modal' ).fadeOut(200);
}

To elebaorate... If you aren't using jQuery Mobile (or some other plugin / extension that defines "tap") then you do not have access to the "tap" event.

There are a number of solutions that will capture a tap event that are not jquery mobile and aren't as hefty if all you need is access to "tap".

More about "touchstart" and other native js touch events here

HelloWorld
  • 2,480
  • 3
  • 28
  • 45