jQuery Backstretch

Thought I’d blog my first proper stackoverflow answer;

http://stackoverflow.com/questions/7125499/use-backstretch-inside-a-division-and-reduce-width-to-width-of-division/10209027#10209027

Let’s see it get downvoted into the bowels of the earth 🙂

I wanted to use backstretch to fill an element which was full width but took up only the top 560px of the screen. And if the image had to be resized larger than the original it didn’t recenter vertically but was offset so the top disappeared.

Yes, the link above is correct, you change the container from the body to the element you want to fill, in this case it was #backimage;

// Append the container to the #backimage, if it's not already there
  if($("#backimage #backstretch").length == 0) {
     $("#backimage").append(container);
  }

Then I changed the code to assign a fixed height css to the image loaded rather than 100%;

// If this is the first time that backstretch is being called
   if(container.length == 0) {
       container = $("<div />").attr("id", "backstretch")
                   .css({left: 0, top: 0, position: "fixed", overflow: "hidden", zIndex: -999999, margin: 0, padding: 0, height: "560", width: "100%"});
    } else {
       // Prepare to delete any old images
        container.find("img").addClass("deleteable");
    }

To achieve this the _adjustBG method has to be changed quite a bit. First of all you need to give the imgWidth and imgHeight variables a global scope. Remove them from;

var self = $(this);

and add them to;

rootElement = ("onorientationchange" in window) ? $(document) : $(window), 
imgRatio, bgImg, imgWidth, imgHeight, bgWidth, bgHeight, bgOffset, bgCSS;

Finally I rewrote a chunk of the _adjustBG method to use the imgWidth and imgHeight rather than have it all basedon the detected browser width and height.


function _adjustBG(fn) {
try {
bgCSS = {left: 0, top: 0}
bgWidth = rootElement.width();
bgHeight = bgWidth / imgRatio;

if( bgHeight <= 560 ) { bgHeight = 560; bgWidth = 560 * imgRatio; bgOffset = ( bgWidth - rootElement.width() ) / 2; if(settings.centeredY) $.extend(bgCSS, {left: "-" + bgOffset + "px"}); } else { bgHeight = (rootElement.width() / imgRatio); bgWidth = rootElement.width() bgOffset = ( bgHeight - 560 ); if(settings.centeredY) $.extend(bgCSS, {top: "-" + bgOffset + "px"}); } $("#backstretch, #backstretch img:last").width( bgWidth ).height( bgHeight ) .filter("img").css(bgCSS); } catch(err) { // IE7 seems to trigger _adjustBG before the image is loaded. // This try/catch block is a hack to let it fail gracefully. } // Executed the passed in function, if necessary if (typeof fn == "function") fn(); }