V
V
Vitaliy Petrov2014-05-05 18:48:43
JavaScript
Vitaliy Petrov, 2014-05-05 18:48:43

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

2 answer(s)
I
Ivan, 2014-05-05
@0neS

iOS and JS "click" event
Not it?

Z
Zlatoslav Desyatnikov, 2014-12-21
@pxz

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);
});

Possibly shitcode. It would be great if someone points out the flaws.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question