Parallax HTML5

http://www.feelouttheform.net/html5-parallax/

by nicolasform

HTML

<!-- The container of the image -->
<p id="parallax1"></p>

<!-- The script that configure the container -->
<script>
    /* write_parallax(
        id of the container,
        url of the image,
        width of the original image in px,
        height of the original image in px);
    */
    write_parallax(
        'parallax1',
        'http://www.stopeen.com/wp-content/uploads/stopeen_header2-e1416268138199.jpg',
        1136,
        539);
</script>

CSS

.parallax {
    width: 100%;
    height: 0;
    padding-bottom: 30%;
}

JavaScript

/*
    GET_BACKGROUND_HEIGHT
    Get the height of the complete resized background image.
        element: the container of the image,
        w: the width of the original image,
        h: the height
        RETURN: the height of the complete resized background image
*/
function get_background_height(element, w, h) {
    // If width or height are not specified
    if (w == null || h == null) {
        // Create an image in memory
        var image = new Image();
        // Get the background image url of the container
        var imageSrc = element.style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];
        // Assign the image to the source
        image.src = imageSrc;
        // Get the width and height of the image
        // BE CAREFUL: on chrome and IE, image.height and image.width return 0 if this is called during the document loading !!!
        w = image.width;
        h = image.height;
    }
    // Calculate the height proportionnaly to the width of the container
    return (h * element.getBoundingClientRect().width / w);
}

/*
    SET_BACKGROUND_OFFSET
    Move the background image according to the container position and the window position
        p: the container
        pYOffset: the offset of the container relatively to the current window
        pHeight: the height of the container
        bgHeight: the height of the background image
*/
function set_background_offset(p, pYOffset, pHeight, bgHeight) {
    // Calculate the offset of background image relatively to the container. It should be the same as the position of the container relatively to the window.
    var bgYOffset = pYOffset * (pHeight - bgHeight) / window.innerHeight;
    // Position the background image with the new offset
    p.style.backgroundPosition = "0px " + bgYOffset + "px";
}

/*
    DO_PARALLAX
    Run the parallax computing on the specified container
        p: the container
        w: the width of the original image
        h: the height of the...