jQuery: How can I create a simple overlay?
Asked Answered
K

7

97

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

What is a lightweight plugin?

Kampala answered 12/11, 2009 at 0:2 Comment(0)
H
206

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..

Housecarl answered 12/11, 2009 at 0:51 Comment(9)
This doesn't work in IE8. The "overlay" is shown below content. Any ideas how to fix this?Lathrope
@Lathrope 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.Housecarl
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.Lathrope
Got it. Had to change doctype from <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.1 Transitional//EN"> to <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> to make IE understand "position: fixed".Lathrope
Nice! Thanks! I'm gonna share your discovery on the question to make it easier on Googler's passing by! ;)Housecarl
what if you cant change the doctype because its a remote page - any ideas how to fix it?Chanachance
@Tobias this is the easy, fast, css solution. I guess you could probably try something javascript based.Housecarl
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.Handset
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');Theriault
G
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

Guarded answered 7/8, 2014 at 15:58 Comment(1)
A <table>? Is it the 1990s?Perspective
M
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 + "]");
        }
    }
)();
Macadamia answered 20/1, 2014 at 15:47 Comment(0)
E
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

Epps answered 30/8, 2016 at 19:31 Comment(0)
S
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?

Stout answered 12/11, 2009 at 0:7 Comment(5)
which lightweight overlay plugin is there ?Kampala
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.Delenadeleon
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.Stout
If you suggest using a plugin you should suggest one or more that you find suitable. Otherwise the answer is not really helpful ...Resent
@Resent - 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.Stout
C
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.

Cathey answered 12/11, 2009 at 0:9 Comment(0)
M
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.

Marathon answered 12/11, 2009 at 0:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.