How to add an overlay DIV to cover an existing DIV (using JQuery)?

Zach picture Zach · Dec 7, 2012 · Viewed 36k times · Source

I have a 'container' DIV which may have all possible CSS styles like: margin, padding, border and different position (fixed, relative, absolute).

I want to show a loading icon above the 'container' DIV and forbid the user to operate any control in the 'container' DIV.

<div class="container">
 A lot of content here ...
</div>

How can I add an overlay DIV (using JQuery) which covers the entire 'container' DIV visible area (margin area should not be covered)?

Best regards, Zach

Answer

VisioN picture VisioN · Dec 7, 2012

If nothing to change in CSS, then:

$("<div />").css({
    position: "absolute",
    width: "100%",
    height: "100%",
    left: 0,
    top: 0,
    zIndex: 1000000,  // to be on the safe side
    background: "url(/img/loading.gif) no-repeat 50% 50%"
}).appendTo($(".container").css("position", "relative"));

$("<div>Loading...</div>").css({
  position: "absolute",
  width: "100%",
  height: "100%",
  top: 0,
  left: 0,
  background: "#ccc"
}).appendTo($(".container").css("position", "relative"));
.container {
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="container">
  A lot of content here ...
</div>

DEMO: http://jsfiddle.net/jKfTC/