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
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
You should use the touchstart
and touchend
events with touch devices:
$(document).on("click touchend", function(){
$(".dropdown-toggle").removeClass("open");
});
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');
}
}
});
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');
}
});