Ryan Sayles
Ryan Sayles

Reputation: 3441

Javascript prevent underlying click when hiding overlay

I'm making an application that runs on desktop and mobile that has a div and when the user either clicks or taps outside of the div it hides. This div is on top of other elements and the issue I'm running into is when the user taps outside of the div it does hide, but then it also performs the click event on an element that is below it. This functionality works fine on desktop when calling the mousedown event. The code that I added in is:

$(document).on( "mousedown touchstart", function(e){
    if (isSearchOpen) {
        if (!$(searchContainer).is(e.target) && $(searchContainer).has(e.target).length === 0) {
            $('input[name=q]','form[name=searchFormMobile]').val('');
            $('input[name=q]','form[name=searchForm]').val('');
            $(searchOverlay).hide();
            isSearchOpen = false;
        }
    }
});

I have tried calling e.preventDefault(), e.stopPropagation(), and return false; within the second if-statement and none of those work. This pop up can appear on mulitple "pages" so I would like to avoid trying to capture any possible element that can be clicked on and handling this issue that way if possible.

Any help would be much appreciated!

Upvotes: 0

Views: 535

Answers (2)

user3235186
user3235186

Reputation:

Append a transparent div with full screen width and height with z-Index 100, and for your DIV, give the z-Index as 101. For Onclick event on the overlay DIV, remove both the DIVs from DOM. FYI, jquery-Ui modal dialog does the same. ;)

Upvotes: 0

polskais1
polskais1

Reputation: 186

You can try adding a blur event to your div instead. Whenever a user clicks or taps outside of the div, an event fires off.

https://developer.mozilla.org/en-US/docs/Web/Events/blur

Upvotes: 1

Related Questions