trigger - onclick javascript

Event on a click everywhere on the page outside of the specific div (6)

Add this:

$('#somediv').click(function(e) {
}).children().click(function(e) {

Here's your updated working fiddle:

I'd like to hide a div when user click anywhere on the page outside of that div. How can I do that using raw javascript or jQuery?

Alternatively you could create another div beneath .myProfile that takes up all the space on your page. To the click event of this div you hide both this special layer and your profile view/box. This is a very common way to implement the modal box. This way you don't have to listen on all other elements.

I believe that this is also the way it is done by the popular Lightbox 2 and definitely used in my own very unpopular code hehe.

First idea, in raw javascript (from this post):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "">
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <style type="text/css">
        background-color: #999999;
        height: 100px;
        width: 100px;
    <script type="text/javascript">
      function check(e)
        var target = (e && || (event && event.srcElement);
        var obj = document.getElementById('mydiv');
    <div id="mydiv">my div</div>

Tested with IE6 and FireFox3.1, it does work as advertised.

I'd do it like so:

$(function () {
    var elem = $( '#somediv' )[0];

    $( document ).click( function ( e ) {
        if ( !== elem ) {
            $( elem ).hide();

Live demo:

So this

var elem = $( '#somediv' )[0];

caches the reference to the DIV element. We want to cache this reference on page load, so that we don't have to query for that element repeatedly. And it improves the readability of the code, also.

How to detect a click on anything other than this one div in jQuery?


  if (!$('myProfile'))


How to make a click on a child element not be considered a click on it's parent in jQuery?

You can compare the click's target to the element in question:

$(document).click(function(e) {
    if ( != $('#somediv')[0]) {