Answer the question
In order to leave comments, you need to log in
How to determine that a click/tap (IOS) occurred on a non-specific element(s)?
Good day everyone,
there is a self-written dropdown, when you click on the input, a list appears. when the list appears, an object is added to it that monitors mouse clicks. On desktop browsers, everything works fine, but on mobile Safari, it doesn’t work like that, it instantly closes.
Here is the code for the object that watches the mouse:
// Detects when user clicks outside of specified element.
function ClickOutsideTracker() {
var isMouseOver = null;
var element;
var onClickOutside;
this.assign = function(_element, _onClickOutside) {
isMouseOver = false;
element = _element;
onClickOutside = _onClickOutside;
element.mouseenter(function () {
isMouseOver = true;
}).mouseleave(function () {
isMouseOver = false;
});
if (isIOS()) {
$(document.body).click(globalOnClickHandler);
?
} else {
$(document.body).mousedown(globalOnClickHandler);
}
return this;
};
function globalOnClickHandler() {
if (!isMouseOver) {
onClickOutside();
}
}
this.unassign = function() {
element.off("mouseenter");
element.off("mouseleave");
if (isIOS()) {
$(document.body).off("click");
} else {
$(document.body).off("mousedown");
}
}
}
Answer the question
In order to leave comments, you need to log in
In general, you need a handler for all clicks on the page, then you already check whether that element was clicked (as well as its descendants) or outside of it.
$(document).on('click', function(event) {
if(!($(event.target).closest(element).size() > 0 || $(event.target).is(element))) {
console.log('Click outside');
} else
console.log('Click inside on',event.target);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question