I have a div and want to hide it when I click outside. My code is:

&lt;div id="mydiv"&gt;The div must be above button&lt;/div&gt;

    $('#mydiv').click(function(e) {
        e.stopPropagation();
    });

    $(document).click(function() {
        $('#mydiv').fadeOut(300);
    });


But it is not working for me ...

UPDATE

Full code is presented below. When I click on a button it shows a div above, so I need to hide this div when I click outside.

DEMO

&lt;div id="but" style="text-align: right;"&gt;&lt;button type="button"&gt;Show Div!&lt;/button&gt;&lt;/div&gt;
&lt;div id="mydiv" style="display:none;"&gt;The div must be above button&lt;/div&gt;

$("#but button").click(function(){
  var pos = $(this).offset(),
      div = $("#mydiv");

  // Make it visible off-page so
  // we can measure it
  div.css({
    "display": "block",
    "border": "1px solid black",
    "position": "absolute",
    "left": -10000,
    "top": 0
  });

  // Move it where we want it to be
  div.css({
    "left": pos.left - 40,
    "top":  pos.top - div.height() - 10
  });
});

$('#myDiv').click(function(e) {
    e.stopPropagation();
});
$(document).click(function() {
    $('#mydiv').fadeOut(300);
});



Question: What are the best tips for saving money as a university student?
Answer: Here's a few:


If your plan results in carrying $100k in student debt at the end, you need a new plan.
Don't drink unless someone else is paying, or if you're buying a special.
Don't live beyond your means.