Hamster
Hamster

Reputation: 3132

Getting an image popup overlay to work

First, code:

CSS:

.popup_foreground {
    position:   fixed;
    top:    0px;
    left:    0px;
    width:    100%;
    height:    100%;
    vertical-align:  middle;
    text-align:   center;
    z-index:   1;
}
.popup_foreground_container {
    margin:    auto;
    padding:   24px;
    background-color: white;
    border:    1px solid black;
    display:   inline-block;
    display:   -moz-inline-stack;
    max-width:   100%;
    max-height:   100%;
    z-index:   2;
}
.popup_image {
    max-height:   100%;
}

Javascript:

function popupImage( img )
{
    var fg = $( "<div class='popup_foreground'></div>" );
    var container = $( "<div class='popup_foreground_container'></div>" );
    var image = $( "<img class='image_full popup_image' src='"+img+"' />" );
    fg.append( container );
    container.append( image );

    $("body").append( fg );

    fg.click( function(){
        fg.remove();
    });
}

Seems to work. Just calling function popupImage() displays the given image as an overlay that can be turned off with a click. In english, there's a foreground element that is fixed to the view, a 'container' with no preset size (only padding), and an image that goes inside of the container.

My problem is that an image larger than the width or height of the screen gets squeezed out of proportion in order to fit. I really can't have that. I don't want to have to use scrolling. How can I get images to scale proportionally to fit in the browser window?

Upvotes: 3

Views: 2170

Answers (1)

David Thomas
David Thomas

Reputation: 253318

If you change the container.append() line to:

container.append( $( "<img class='image_full popup_image' src='"+img+"' width='"+ $(container).width() +"'/>" ) );

It should assign the width of the container element to the created img. This might be a problem, though, for smaller images so it might be worth using an if/else statement to check whether the scaling is required.

Using only width means that the image will be scaled proportionally, whereas if you set height (as well as width) the image is likely to be distorted.

Upvotes: 2

Related Questions