jQuery: creating a splash screen effect without Flash

Popups are dinosaurs. Though today they've been actually revitalized by Flash, they're still something heavy, clumsy and clunky. When a visitor enters our page, we want something cool happen, without wasting our time with searching the entire web for a good tutorial on Flash popups. So it's jQuery. What we want is some kind of animation, like a splash screen, that takes place when the page is finished loading. So it's a box, a div, with some content inside, first hidden and then revealed in time.

Our box might have the following styles:

#test {
    
    background: orange;
    width: 0px;
    position: absolute;
    overflow: hidden;
    font-size: 7em;
    text-align: center;
    color: #fff;
    font-family: Impact, sans-serif;
    letter-spacing: 0.1em;
    
}

The width of the box is zeroed and we prevent any overflow of content from happening thanks to the overflow property. Absolute positioning is required here to work with jQuery animations. Now jQuery. First, we want a box with proportional dimensions, using the whole document object as a reference. Then, this box must be horizontally and vertically centered within the viewport. Here's the jQuery code:

$(document).ready(function() {
    
    
    var docWidth = $(document).width();
    var docHeight = $(document).height();
    
    var divWidth = Math.round(docWidth / 2);
    var divHeight = Math.round(docHeight / 2);
    
    var offsetLeft = '50%';
    var offsetTop = '50%';
    
    $('#test').animate(
                   {
                   width: divWidth,
                   height: divHeight,
                   top: offsetTop,
                   left: offsetLeft,
                   marginTop: -(divHeight / 2),
                   marginLeft: -(divWidth / 2),
                   lineHeight: divHeight
                   
                   
                   
                   }, 'slow');
    
    
    
});

Our box is half of the dimensions of the whole page. The CSS trick used here is pretty simple: to center an element within the viewport, use the top and left properties set to 50%. Then use negative values for the margin-top and margin-left properties. These values must be the half of the height and width of the element, respectively.

What else? You can add a lot of improvements to this code. You can make the element disappear, or create a closing button. The only limit is your imagination. Goodbye Flash.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: creating a splash screen effect without Flash”

Leave a Reply

Note: Only a member of this blog may post a comment.