Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Backstretch can now be applied to multiple DIVs #93

Closed
wants to merge 2 commits into from
@timnovinger

This adds the ability to apply the backstretch to multiple DIV containers, instead of only the Body of a page, along with additional CSS options to go with it.

timnovinger added some commits
@timnovinger timnovinger Backstretch can now be applied to multiple DIVs
This commit includes additional options and the ability to apply
the backstretch to multiple DIV containers, instead of only the
BODY of a page.
ce988ef
@timnovinger timnovinger Updated minified version ebe0652
@srobbin
Owner

This is awesome! Thanks, Tim.

I'm going to be adding in a couple more features for the next release, so it might be a week or so before I pull in the changes. Still, I really appreciate this pull. Thanks so much.

@timnovinger

Here is an example of some of the new usage:

$.backstretch(IMAGE_SRC, {
'target': DIV_ID,
'speed': TIME_IN_MS_OR_JQUERY_KEYWORD,
'positionType': 'absolute',
'zIndex': 0
});

@kvcrawford

Love the plugin, thanks for sharing your work guys. It'd be really awesome if this pull request was added!

@paulmolluzzo

This is an awesome update to the plugin! Used this source over the original...

@Greg0497

Hi,
I'm interested in having a full screen pic for each #div (each page on my single page website
Unfortunately I'm not sure how to use the code above.
Should I copy it 3x in my html page (one per #div)
What do I need to put for speed?
And for DIV_ID to I need to put brackets or something?
Many thanks,

@timnovinger

@Greg0497

  • Yes, you would need to declare the backstretch per each div you want to apply it to.
  • No sure? I suppose you could cache the container of the div to a variable and then use .find() to search within it, although if the container is $('body') then this is pretty pointless.

    var $container = $('#page-wrapper') and then $container.find('#my-div')

  • Simply use a string of the ID for DIV_ID, such as 'target': '#my-div'

@Greg0497

thanks Tim!

@johntuesday

Hey,
Really cool, I've been searching for this ;)
But it doesn't work for me ;)
Here's what i'm creating
http://the-weeknd.com/

I have a single page in 3 Main Div (page1 - page3)
The first BG fits perfectly, but if I target the same (or another) Image to set on my "page2" Div, nothing happends =(

is this right?

Hope you can help me ;)

@Sebah

Hi,

I'm wondering about the same thing as 'johntuesday.
Basically I have a single page website with vertical scroll, each div fiting the screen size ( I'm doing this via jQuery, on document.load ). The problem I'm having is that the it's only applying backstretch to the last div from the script:

$.backstretch('img/bg/home.jpg', {
'target': '#home',
'speed': '1',
'positionType': 'absolute',
'zIndex': -2
});
$.backstretch('img/bg/agepage.jpg', {
'target': '#agePage',
'speed': '1',
'positionType': 'absolute',
'zIndex': -1
});

and the width that is setting is longer than the container...

@paulmolluzzo

I'm pretty sure that the issue everyone is experiencing has to do with the positionType which has a default setting of fixed. Since a few people are having issues with applying backstretch multiple times, I'll paste in my code so you can see how I did it. This is working just fine for me in vertically stacked divs.

This is in the HTML above </body>.

            $.backstretch('images/image1.jpg', {
            'target': '#one',
            'speed': 1000,
            'positionType': 'relative',
            });

            $.backstretch('images/image2.jpg', {
            'target': '#two',
            'speed': 1000,
            'positionType': 'relative',
            });

            $.backstretch('images/image3.jpg', {
            'target': '#three',
            'speed': 1000,
            'positionType': 'relative',
            }); 

Also, a tip/issue when using backstretch on vertical divs is in regards to responsive design. I adjusted the heights of the divs at specific breaks so that it flowed nicer. I suppose you could include some JS that resizes the height dynamically, but that's another story...

Here's an example with an (abridged) media query I'm using:

.section {
    width: auto;
    height: 825px;
    margin: 0px auto -20px auto;
    overflow: hidden;
}
.
.
.
@media screen and (max-width:500px) {
    .section {
    height: 540px;
    }
}
@Sebah

@paulmolluzzo - thanks for your reply mate.
I've played with the script's settings and still didn't get the result I was expecting.

Basically I have my 3 DIV's aligned vertically on the page ( I'm setting the width & height via css, not JS ) and the backstretch images are being rendered, but only the last one in the chain goes 100% width & height, the other 2 ( so the first 2 ) only showing the image at its original dimensions.

Did you run into the same issue?

@kohloth

Hmm...this is frustrating. I can get it to work in the usual way;

$.backstretch("pot-holder.jpg");

and the div way when using HTML element tags;

$.backstretch("<?php echo $this->baseurl ;?>/templates/<?php echo $this->template ;?>/images/text-bg.jpg", {
'target': 'html';
});

and

$.backstretch("<?php echo $this->baseurl ;?>/templates/<?php echo $this->template ;?>/images/text-bg.jpg", {
'target': 'head';
});

$.backstretch("<?php echo $this->baseurl ;?>/templates/<?php echo $this->template ;?>/images/text-bg.jpg", {
'target': '*';
});

Which all append the div appropriately. However, the following:

$.backstretch("<?php echo $this->baseurl ;?>/templates/<?php echo $this->template ;?>/images/text-bg.jpg", {
'target': ''#myDiv'
});

Doesn't do anything at all. Theres no prepended divs there in the source code at all. Have tried with and without the "#" before the div name, different divs, and even div.myDiv etc...

@gamecat2300

Wow Man! I'm kind of in love with you... Thanks a million!

@tscok

I'm having the same problem as @Sebah

I have a vertical, two DIV layout. Both DIV's have the following CSS:
width: 100%;height: 320px;overflow: hidden;

The two DIV ID's are "#img1" and "#img2"

The code I run is what @paulmolluzzo posted above:

$.backstretch('folder/img1.jpg', {
  'target': '#img1',
  'speed': 1000,
  'positionType': 'relative',
});

$.backstretch('folder/img2.jpg', {
  'target': '#img2',
  'speed': 1000,
  'positionType': 'relative',
});

While img2.jpg gets stretched, img1 remains unstretched. It doesn't matter if I change the order in the script, it's always the last one that gets affected by the stretch.

I've tested this in both FF 14 and IE 8 - same problem. The code I have taken from GitHub so it should be the latest version I guess. The jQuery library I'm using is http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js if that would matter?

It's really frustrating since I love what it does.. or would do if it worked =)

@srobbin
Owner

Hi Everyone,

I've got a new version of Backstretch in progress that adds this functionality, and makes it easier to do slideshows. Would you mind taking a look, giving it a spin, and letting me know if you have any troubles or thoughts?

Thank you, again, to @timnovinger for submitting his excellent patch, and for inspiring this thread. I chose to refactor much of the plugin, so his changes couldn't be merged, though they were very helpful in guiding the implementation.

https://github.com/srobbin/jquery-backstretch/tree/2.0.0-wip

@srobbin srobbin closed this
@christopherkoelsch

Hi having a problem with no images loading for the past 5 days of trying with backstretch. Checked all my file paths, have proper library plugins, checking order of markup, checked order of scripts. Any ideas? please help!

Here is my code:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<head profile="http://gmpg.org/xfn/11">
<link rel="stylesheet" href="new_website/new_site_css/stylesheet2.css" type="text/css" media="screen" title="CSS" charset="utf-8" />
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">


I don't have any css declared, FYI. Thanks so much!

@eladnova

@ christopherkoelsch

Have a live URL we can look at?

@christopherkoelsch
@kvcrawford

@christopherkoelsch change the following lines:

<link rel="stylesheet" href="new_website/new_site_css/stylesheet2.css" type="text/css" media="screen" title="CSS" charset="utf-8" />
<script type="text/javascript" src="new_website/jquery.backstretch.js"></script>

to

<link rel="stylesheet" href="./new_site_css/stylesheet2.css" type="text/css" media="screen" title="CSS" charset="utf-8" />
<script type="text/javascript" src="./jquery.backstretch.js"></script>

or prefix the "new_website" part with a "/" to make it an absolute URL: "/new_website/jquery.backstretch.js"

@christopherkoelsch
@eladnova

Chris - I can't see where you are telling backstretch which block level element you want the image applied to?

Then again, I normally apply it to a DIV so that might not be the issue.

Why dont you try applying it to a DIV for the moment and we might be able to narrow it down?

@eladnova

Chris - I downloaded your page and files and got it working on your body tag.
Have a look for multiple opening html tags in your code. When I 'view source', I see two tags.

Next up is your paths issue. If you want, I can forward you a zipped up folder of my working demo.

@christopherkoelsch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Feb 29, 2012
  1. @timnovinger

    Backstretch can now be applied to multiple DIVs

    timnovinger authored
    This commit includes additional options and the ability to apply
    the backstretch to multiple DIV containers, instead of only the
    BODY of a page.
  2. @timnovinger

    Updated minified version

    timnovinger authored
This page is out of date. Refresh to see the latest.
Showing with 65 additions and 37 deletions.
  1. +54 −35 jquery.backstretch.js
  2. +11 −2 jquery.backstretch.min.js
View
89 jquery.backstretch.js
@@ -1,59 +1,75 @@
/*
* jQuery Backstretch
- * Version 1.2.5
+ * Version 1.3
* http://srobbin.com/jquery-plugins/jquery-backstretch/
+ * http://github.com/colorjar/jquery-backstretch/
*
* Add a dynamically-resized background image to the page
*
+ * This is a fork of SRobbin's original 1.2.2 script.
+ * It includes additional options and the ability to apply
+ * the backstretch to multiple DIV containers, instead of
+ * only the BODY of a page.
+ *
+ * ColorJar Author
+ * Tim Novinger | http://github.com/timnovinger
+ *
* Copyright (c) 2011 Scott Robbin (srobbin.com)
* Dual licensed under the MIT and GPL licenses.
*/
-;(function($) {
+(function($) {
$.backstretch = function(src, options, callback) {
var defaultSettings = {
- centeredX: true, // Should we center the image on the X axis?
- centeredY: true, // Should we center the image on the Y axis?
- speed: 0 // fadeIn speed for background after image loads (e.g. "fast" or 500)
+ target: 'body', // Apply on BODY by default or on a passed in element ID
+ injectUsingPrepend: false, // Append by default or prepend by passing in TRUE
+ positionType: 'fixed', // Normal CSS position types of relative, fixed, absolute
+ centeredX: true, // Should we center the image on the X axis?
+ centeredY: true, // Should we center the image on the Y axis?
+ zIndex: '-999999', // Option to pass in z-index value, if backstretch is being applied to a normal DIV this can be useful
+ speed: 0 // fadeIn speed for background after image loads (e.g. "fast" or 500)
},
- container = $("#backstretch"),
- settings = container.data("settings") || defaultSettings, // If this has been called once before, use the old settings as the default
+ container = $(".backstretch"),
+ settings = container.data("settings") || defaultSettings, // If this has been called once before, use the old settings as the default
existingSettings = container.data('settings'),
- rootElement = ("onorientationchange" in window) ? $(document) : $(window), // hack to acccount for iOS position:fixed shortcomings
imgRatio, bgImg, bgWidth, bgHeight, bgOffset, bgCSS;
-
+
// Extend the settings with those the user has provided
if(options && typeof options == "object") $.extend(settings, options);
-
- // Just in case the user passed in a function without options
- if(options && typeof options == "function") callback = options;
-
+
+ if (settings.target == 'body'){
+ // hack to acccount for iOS position:fixed shortcomings
+ rootElement = ("onorientationchange" in window) ? $(document) : $(window);
+ } else {
+ rootElement = $(settings.target);
+ }
+
// Initialize
$(document).ready(_init);
-
+
// For chaining
return this;
-
+
function _init() {
- // Prepend image, wrapped in a DIV, with some positioning and zIndex voodoo
+ // Inject image, wrapped in a DIV, with some positioning and zIndex voodoo
if(src) {
var img;
-
+
// 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: "100%", width: "100%"});
+ container = $("<div />").attr("class", "backstretch")
+ .css({left: 0, top: 0, position: settings.positionType, overflow: "hidden", zIndex: settings.zIndex, margin: 0, padding: 0, height: "100%", width: "100%"});
} else {
// Prepare to delete any old images
container.find("img").addClass("deleteable");
}
-
- img = $("<img />").css({position: "absolute", display: "none", margin: 0, padding: 0, border: "none", zIndex: -999999})
- .bind("load", function(e) {
+
+ img = $("<img />").css({position: "absolute", display: "none", margin: 0, padding: 0, border: "none", zIndex: settings.zIndex})
+ .bind("load", function(e) {
var self = $(this),
imgWidth, imgHeight;
-
+
self.css({width: "auto", height: "auto"});
imgWidth = this.width || $(e.target).width();
imgHeight = this.height || $(e.target).height();
@@ -67,30 +83,33 @@
if(typeof callback == "function") callback();
});
});
-
+
})
.appendTo(container);
-
+
// Append the container to the body, if it's not already there
- if($("body #backstretch").length == 0) {
- $("body").append(container);
+ var $target = $(settings.target),
+ injection_type = settings.injectUsingPrepend ? 'prepend' : 'append';
+
+ if($target.is('*') && $target.find('.backstretch').length == 0) {
+ $target[injection_type](container);
}
-
+
// Attach the settings
container.data("settings", settings);
-
+
img.attr("src", src); // Hack for IE img onload event
// Adjust the background size when the window is resized or orientation has changed (iOS)
$(window).resize(_adjustBG);
}
}
-
+
function _adjustBG(fn) {
try {
bgCSS = {left: 0, top: 0}
bgWidth = rootElement.width();
bgHeight = bgWidth / imgRatio;
-
+
// Make adjustments based on image ratio
// Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
if(bgHeight >= rootElement.height()) {
@@ -103,16 +122,16 @@
if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
}
- $("#backstretch, #backstretch img:not(.deleteable)").width( bgWidth ).height( bgHeight )
- .filter("img").css(bgCSS);
+ $(".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();
}
};
-
+
})(jQuery);
View
13 jquery.backstretch.min.js
@@ -1,11 +1,20 @@
/*
* jQuery Backstretch
- * Version 1.2.5
+ * Version 1.3
* http://srobbin.com/jquery-plugins/jquery-backstretch/
+ * http://github.com/colorjar/jquery-backstretch/
*
* Add a dynamically-resized background image to the page
*
+ * This is a fork of SRobbin's original 1.2.2 script.
+ * It includes additional options and the ability to apply
+ * the backstretch to multiple DIV containers, instead of
+ * only the BODY of a page.
+ *
+ * ColorJar Author
+ * Tim Novinger | http://github.com/timnovinger
+ *
* Copyright (c) 2011 Scott Robbin (srobbin.com)
* Dual licensed under the MIT and GPL licenses.
*/
-;(function(a){a.backstretch=function(l,b,j){function m(c){try{h={left:0,top:0},e=f.width(),d=e/k,d>=f.height()?(i=(d-f.height())/2,g.centeredY&&a.extend(h,{top:"-"+i+"px"})):(d=f.height(),e=d*k,i=(e-f.width())/2,g.centeredX&&a.extend(h,{left:"-"+i+"px"})),a("#backstretch, #backstretch img:not(.deleteable)").width(e).height(d).filter("img").css(h)}catch(b){}"function"==typeof c&&c()}var n={centeredX:!0,centeredY:!0,speed:0},c=a("#backstretch"),g=c.data("settings")||n;c.data("settings");var f="onorientationchange"in window?a(document):a(window),k,e,d,i,h;b&&"object"==typeof b&&a.extend(g,b);b&&"function"==typeof b&&(j=b);a(document).ready(function(){if(l){var b;0==c.length?c=a("<div />").attr("id","backstretch").css({left:0,top:0,position:"fixed",overflow:"hidden",zIndex:-999999,margin:0,padding:0,height:"100%",width:"100%"}):c.find("img").addClass("deleteable");b=a("<img />").css({position:"absolute",display:"none",margin:0,padding:0,border:"none",zIndex:-999999}).bind("load",function(b){var d=a(this),e;d.css({width:"auto",height:"auto"});e=this.width||a(b.target).width();b=this.height||a(b.target).height();k=e/b;m(function(){d.fadeIn(g.speed,function(){c.find(".deleteable").remove();"function"==typeof j&&j()})})}).appendTo(c);0==a("body #backstretch").length&&a("body").append(c);c.data("settings",g);b.attr("src",l);a(window).resize(m)}});return this}})(jQuery);
+(function(a){a.backstretch=function(b,c,d){function p(b){try{n={left:0,top:0};k=rootElement.width();l=k/i;if(l>=rootElement.height()){m=(l-rootElement.height())/2;if(g.centeredY)a.extend(n,{top:"-"+m+"px"})}else{l=rootElement.height();k=l*i;m=(k-rootElement.width())/2;if(g.centeredX)a.extend(n,{left:"-"+m+"px"})}a(".backstretch, .backstretch img:last").width(k).height(l).filter("img").css(n)}catch(c){}if(typeof b=="function")b()}function o(){if(b){var c;if(f.length==0){f=a("<div />").attr("class","backstretch").css({left:0,top:0,position:g.positionType,overflow:"hidden",zIndex:g.zIndex,margin:0,padding:0,height:"100%",width:"100%"})}else{f.find("img").addClass("deleteable")}c=a("<img />").css({position:"absolute",display:"none",margin:0,padding:0,border:"none",zIndex:g.zIndex}).bind("load",function(b){var c=a(this),e,h;c.css({width:"auto",height:"auto"});e=this.width||a(b.target).width();h=this.height||a(b.target).height();i=e/h;p(function(){c.fadeIn(g.speed,function(){f.find(".deleteable").remove();if(typeof d=="function")d()})})}).appendTo(f);var e=a(g.target),h=g.injectUsingPrepend?"prepend":"append";if(e.is("*")&&e.find(".backstretch").length==0){e[h](f)}f.data("settings",g);c.attr("src",b);a(window).resize(p)}}var e={target:"body",injectUsingPrepend:false,positionType:"fixed",centeredX:true,centeredY:true,zIndex:"-999999",speed:0},f=a(".backstretch"),g=f.data("settings")||e,h=f.data("settings"),i,j,k,l,m,n;if(c&&typeof c=="object")a.extend(g,c);if(g.target=="body"){rootElement="onorientationchange"in window?a(document):a(window)}else{rootElement=a(g.target)}a(document).ready(o);return this}})(jQuery)
Something went wrong with that request. Please try again.