26

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

Zach
  • 5,715
  • 12
  • 47
  • 62

1 Answers1

64

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/

Satpal
  • 132,252
  • 13
  • 159
  • 168
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 1
    Also might be a good idea to check if the `.container` has 'static' positioning before setting it's position... just to make your code reusable. – Ryan Wheale Dec 07 '12 at 01:48
  • 4
    I would recommend having all your styling defined before in your css file rather than applying it on the fly with jQuery. Like so http://jsfiddle.net/jKfTC/1/ – 3dgoo Dec 07 '12 at 03:26
  • If the container has a border, the border is not covered in the solution above. – Zach Dec 07 '12 at 07:43
  • 1
    You could just make the loading container span 1px bigger all the way around like this: http://jsfiddle.net/jKfTC/3/ – 3dgoo Dec 08 '12 at 09:59
  • Also it's z-index not zIndex, for all ya noobs out there! – Cody Django May 27 '14 at 18:16
  • 4
    @Cody It is `z-index` for CSS file and for inline styles of HTML elements. In JavaScript you may use `zIndex` property of `style` object. jQuery can accept both `"z-index"` (key as a string) and `zIndex` (as simple as that). – VisioN May 27 '14 at 18:25