0

I have a div that I hide/show with onclick that adds or removes a css class. I want to be able to close/hide the div when the user clicks outside the div area.

How do I do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bluepinto
  • 165
  • 9
  • 1
    http://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it – Milap Feb 03 '16 at 04:42

2 Answers2

0

I think what you're looking for can be done with JavaScript. Its an event called 'onBlur' which triggers an event handler when something loses focus (e.g. your div).

You can read more about it here: http://www.w3schools.com/jsref/event_onblur.asp

Basically you call a JavaScript function when your object loses focus:

onBlur="myFunction();"

...and 'myFunction()' will have the JavaScript to change your CSS.

Coopza
  • 43
  • 4
0

As mentioned here- https://stackoverflow.com/a/7385673/1982631

HTML

<div class="block">
      <div class="blockelements">

      </div>
    </div>

jQuery-

$(document).bind('click mouseup blur',function (e)
{
    var container = $(".block");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

Demo- https://jsfiddle.net/up6g5rqL/1/

Community
  • 1
  • 1
Manoz
  • 6,507
  • 13
  • 68
  • 114
  • Incredibly it works only when I have the debug console open in firefox. Lol, I'll figure it out, now I'm on the path :) – bluepinto Feb 03 '16 at 07:47