JSFiddle - React, Tailwind, and code Playground

by Matt_Coughlin

CSS

html {
    height: 100%;
}
body {
    height: 100%;
    margin: 0;
    background: url(http://www.forestpath.org/test/misc/img/photos/photo002_640_480.jpg) no-repeat 0 0;
}

JavaScript

function FullBodyBackground(options) {
    if (typeof options == 'undefined' || options === null) options = {};
    var width, height, aspectRatio, contain;
    var self = this;

    this.initialize = function() {
        contain = options.contain;

        if (options.width && options.height) {
            this.setSize(options.width, options.height);
        }
        else {
            var img = new Image();
            img.onload = function() {
                self.setSize(img.width, img.height);
            }
            var url = options.url ||
                  $('body').css('backgroundImage').match(/\("?([^")]*)/)[1];
            if (url) img.src = url;
        }
        return this;
    }

    this.setSize = function(w, h) {
        width = w;
        height = h;
        aspectRatio = width / height;

        this.update();
        $(window).resize(function(){ self.update(); });
    }

    this.update = function() {
        if (!width) return;

        var pageWidth = $(document).width();
        var pageHeight = $(document).height();

        var pageAspectRatio = pageWidth / pageHeight;

        if ((pageAspectRatio > aspectRatio) == !!contain)
            $('body').css({backgroundSize: 'auto ' + pageHeight + 'px'});
        else
            $('body').css({backgroundSize: pageWidth + 'px auto'});
    }
}

FullBodyBackground.init = function(options) {
    (new FullBodyBackground(options)).initialize();
}


$(document).ready(function(){
    FullBodyBackground.init({contain: false});
});