2

I am doing this and it works fine on the desk:

$(document).on("click", function(){
  $(".dropdown-toggle").removeClass("open");
});

But on the iPad that it isn't working and my dropdown remains open

rob.m
  • 9,843
  • 19
  • 73
  • 162
  • Mobile Safari doesn't fire click events unless it deems the element to be clickable; see https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile – cvrebert Jan 29 '15 at 16:36

3 Answers3

4

You should use the touchstart and touchend events with touch devices:

$(document).on("click touchend", function(){
    $(".dropdown-toggle").removeClass("open");
});
meskobalazs
  • 15,741
  • 2
  • 40
  • 63
  • ok yes it worked. however you do need also to include click as it is required for both i guess, so "click touchend" but yes, i will accept. thanks – rob.m Jan 29 '15 at 15:01
  • so touchend is when the user finished to click and touchstart when it starts? or what is the difference in plain words? Thanks – rob.m Jan 29 '15 at 15:02
  • It is exactly as you have said, it is usally preferable to do something when the touch ends, I myself also find it better from an UX standpoint. – meskobalazs Jan 29 '15 at 15:03
2

This answer relates to navbar menus, rather than general dropdowns, but I came across this while looking for the answer to my own similar question (close hamburger menus when tapping outside), so thought I'd post an alternative solution for anyone else, as the accepted answer does not work with hamburger submenus (tapping to open a submenu would close the hamburger menu).

This answer was based on the accepted answer and this answer, as well as NickGreen's comment on this answer.

$('html').on('click, touchend', function (e) {
    // Close hamburger menu when tapping outside
    if ($(e.target).closest('.navbar').length == 0) {
        var opened = $('.navbar-collapse').hasClass('collapse in');
        if (opened === true) {
            $('.navbar-collapse').collapse('hide');
        }
    }
});
Community
  • 1
  • 1
Amy Barrett
  • 564
  • 3
  • 14
  • 27
0

I use this snippet if I don't want to close any dropdown on the page when the user clicks inside it.

$(document).on('click touchend', function(e) {
  if ($(e.target).closest('.open').length === 0) {
    $('.dropdown-toggle').parent().removeClass('open');
  }
});
Michael
  • 105
  • 1
  • 6