What is the easiest way to do a clickout in jquery Where a div box hides if clicked anywhere outside it.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I don’t like the solutions that use
stopPropagationbecause often I am using event bubbling to manage various links. I don’t want to have to worry that they might stop working if the box exists. My choice would look something like this:The
hasfunction filters the selection and returns elements only if they contain the element passed as the parameter (you can also use a selector string, but that isn’t relevant here). If the click was outside the box,lengthwill be0so the conditional will pass and the box will be hidden.This should be optimised by setting a boolean value for whether the box is currently visible and only doing the
hascall if it is currently visible.