97

How can I create a really basic overlay in jQuery without UI?

What is a lightweight plugin?

peterh
  • 11,875
  • 18
  • 85
  • 108
aoghq
  • 1,417
  • 3
  • 13
  • 11

7 Answers7

204

An overlay is, simply put, a div that stays fixed on the screen (no matter if you scroll) and has some sort of opacity.

This will be your CSS for cross browser opacity of 0.5:

#overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    z-index: 10000;
}

This will be your jQuery code (no UI needed). You're just going to create a new element with the ID #overlay. Creating and destroying the DIV should be all you need.

var overlay = jQuery('<div id="overlay"> </div>');
overlay.appendTo(document.body)

For performance reasons you might wanna have the DIV hidden and setting the display to block and none as you need it or not.

Edit: As @Vitaly so well put it, be sure to check your DocType. Read more on the comments on his findings..

starball
  • 20,030
  • 7
  • 43
  • 238
Frankie
  • 24,627
  • 10
  • 79
  • 121
  • This doesn't work in IE8. The "overlay" is shown below content. Any ideas how to fix this? – Vitaly Oct 13 '10 at 09:39
  • @Vitaly are you putting the overlay DIV on the top of the page? with `position:fixed; top:0; left:0` if so let me know and I'll give it a look when I get to the office. – Frankie Oct 13 '10 at 09:46
  • Yes, just like you that. Setting position to "absolute" makes it work, but it doesn't cover the right edge of the document and scrolls with the rest of the content. – Vitaly Oct 13 '10 at 09:47
  • 9
    Got it. Had to change doctype from to to make IE understand "position: fixed". – Vitaly Oct 13 '10 at 10:00
  • 3
    Nice! Thanks! I'm gonna share your discovery on the question to make it easier on Googler's passing by! ;) – Frankie Oct 13 '10 at 10:01
  • what if you cant change the doctype because its a remote page - any ideas how to fix it? – Toby Oct 26 '10 at 22:11
  • @Tobias this is the easy, fast, css solution. I guess you could probably try something javascript based. – Frankie Oct 26 '10 at 23:11
  • 6
    If you want to add content to that overlay but don't want it to be semi opaque, use background:#000000;background-color:rgba(0,0,0,.5) instead of the opacity entries. The background:#000000 before the rgba supports older browsers. – Shanimal Sep 13 '12 at 15:08
  • 3
    TIP: For cross-browser support use 1x1px semi-transparent image (gif or png) ...then you can easily set it as `background-image: url('semi-transparent-pixel.png');` – jave.web Oct 17 '13 at 13:44
18

Here is a simple javascript only solution

function displayOverlay(text) {
    $("<table id='overlay'><tbody><tr><td>" + text + "</td></tr></tbody></table>").css({
        "position": "fixed",
        "top": 0,
        "left": 0,
        "width": "100%",
        "height": "100%",
        "background-color": "rgba(0,0,0,.5)",
        "z-index": 10000,
        "vertical-align": "middle",
        "text-align": "center",
        "color": "#fff",
        "font-size": "30px",
        "font-weight": "bold",
        "cursor": "wait"
    }).appendTo("body");
}

function removeOverlay() {
    $("#overlay").remove();
}

Demo:

http://jsfiddle.net/UziTech/9g0pko97/

Gist:

https://gist.github.com/UziTech/7edcaef02afa9734e8f2

Tony Brix
  • 4,085
  • 7
  • 41
  • 53
3

Here's a fully encapsulated version which adds an overlay (including a share button) to any IMG element where data-photo-overlay='true.

JSFiddle http://jsfiddle.net/wloescher/7y6UX/19/

HTML

<img id="my-photo-id" src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" alt="Photo" data-photo-overlay="true" />

CSS

#photoOverlay {
    background: #ccc;
    background: rgba(0, 0, 0, .5);
    display: none;
    height: 50px;
    left: 0;
    position: absolute;
    text-align: center;
    top: 0;
    width: 50px;
    z-index: 1000;
}

#photoOverlayShare {
    background: #fff;
    border: solid 3px #ccc;
    color: #ff6a00;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    margin-left: auto;
    margin: 15px;
    padding: 5px;
    position: absolute;
    left: calc(100% - 100px);
    text-transform: uppercase;
    width: 50px;
}

JavaScript

(function () {
    // Add photo overlay hover behavior to selected images
    $("img[data-photo-overlay='true']").mouseenter(showPhotoOverlay);

    // Create photo overlay elements
    var _isPhotoOverlayDisplayed = false;
    var _photoId;
    var _photoOverlay = $("<div id='photoOverlay'></div>");
    var _photoOverlayShareButton = $("<div id='photoOverlayShare'>Share</div>");

    // Add photo overlay events
    _photoOverlay.mouseleave(hidePhotoOverlay);
    _photoOverlayShareButton.click(sharePhoto);

    // Add photo overlay elements to document
    _photoOverlay.append(_photoOverlayShareButton);
    _photoOverlay.appendTo(document.body);

    // Show photo overlay
    function showPhotoOverlay(e) {
        // Get sender 
        var sender = $(e.target || e.srcElement);

        // Check to see if overlay is already displayed
        if (!_isPhotoOverlayDisplayed) {
            // Set overlay properties based on sender
            _photoOverlay.width(sender.width());
            _photoOverlay.height(sender.height());

            // Position overlay on top of photo
            if (sender[0].x) {
                _photoOverlay.css("left", sender[0].x + "px");
                _photoOverlay.css("top", sender[0].y) + "px";
            }
            else {
                // Handle IE incompatibility
                _photoOverlay.css("left", sender.offset().left);
                _photoOverlay.css("top", sender.offset().top);
            }

            // Get photo Id
            _photoId = sender.attr("id");

            // Show overlay
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = true;
        }
    }

    // Hide photo overlay
    function hidePhotoOverlay(e) {
        if (_isPhotoOverlayDisplayed) {
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = false;
        }
    }

    // Share photo
    function sharePhoto() {
        alert("TODO: Share photo. [PhotoId = " + _photoId + "]");
        }
    }
)();
wloescher
  • 4,503
  • 2
  • 25
  • 27
1

Please check this jQuery plugin,

blockUI

with this you can overlay all the page or elements, works great for me,

Examples: Block a div: $('div.test').block({ message: null });

Block the page: $.blockUI({ message: '<h1><img src="busy.gif" /> Just a moment...</h1>' }); Hope that help someone

Greetings

Pablo Rodriguez V.
  • 358
  • 1
  • 4
  • 9
0

If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?

Dan Breen
  • 12,626
  • 4
  • 38
  • 49
  • 2
    which lightweight overlay plugin is there ? – aoghq Nov 12 '09 at 00:09
  • 15
    Why borrow a wheel with bells and whistles when you can create a perfectly acceptable wheel in 3 lines of code? Plugins aren't always the best solution. – Joel Nov 12 '09 at 00:55
  • 5
    3 lines of code that might work nicely in FF, but then there might be quirks in some version of IE. At least with a known tool, most of the kinks have already been worked out. – Dan Breen Nov 12 '09 at 01:56
  • 7
    If you suggest using a plugin you should suggest one or more that you find suitable. Otherwise the answer is not really helpful ... – Hinek Oct 13 '10 at 10:21
  • @Hinek - he rephrased the question after I answered. He originally asked for an overlay without using a library and I was suggesting it wasn't much more overhead to use one rather than get frustrated implementing one from scratch. – Dan Breen Oct 13 '10 at 18:04
0

By overlay do you mean content that overlaps/covers the rest of the page? In HTML, you could do this by using a div that uses absolute or fixed positioning. If it needed to be generated dynamically, jQuery could simply generate a div with the position style set appropriately.

Jacob
  • 77,566
  • 24
  • 149
  • 228
0

What do you intend to do with the overlay? If it's static, say, a simple box overlapping some content, just use absolute positioning with CSS. If it's dynamic (I believe this is called a lightbox), you can write some CSS-modifying jQuery code to show/hide the overlay on-demand.

Illianthe
  • 343
  • 3
  • 7