Skip to content
This repository

Backstretch can now be applied to multiple DIVs #93

Closed
wants to merge 2 commits into from
Tim Novinger

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.

added some commits February 29, 2012
Tim Novinger 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
Tim Novinger Updated minified version ebe0652
Scott Robbin
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.

Tim Novinger

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
});

Kevin Crawford

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

Paul Molluzzo

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,

Tim Novinger

@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!

John Tuesday

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 ;)

Sebastian Toporas
Sebah commented July 30, 2012

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...

Paul Molluzzo

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;
    }
}

Sebastian Toporas
Sebah commented July 31, 2012

@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?

ws101a
ws101a commented July 31, 2012

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!

Mikael Carlsson

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 =)

Scott Robbin
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

Scott Robbin srobbin closed this November 26, 2012
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">


eladnova

@ christopherkoelsch

Have a live URL we can look at?

christopherkoelsch
Kevin Crawford

@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

Showing 2 unique commits by 1 author.

Feb 29, 2012
Tim Novinger 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
Tim Novinger Updated minified version ebe0652
This page is out of date. Refresh to see the latest.
89  jquery.backstretch.js
... ...
@@ -1,59 +1,75 @@
1 1
 /*
2 2
  * jQuery Backstretch
3  
- * Version 1.2.5
  3
+ * Version 1.3
4 4
  * http://srobbin.com/jquery-plugins/jquery-backstretch/
  5
+ * http://github.com/colorjar/jquery-backstretch/
5 6
  *
6 7
  * Add a dynamically-resized background image to the page
7 8
  *
  9
+ * This is a fork of SRobbin's original 1.2.2 script.
  10
+ * It includes additional options and the ability to apply
  11
+ * the backstretch to multiple DIV containers, instead of
  12
+ * only the BODY of a page.
  13
+ *
  14
+ * ColorJar Author
  15
+ * Tim Novinger | http://github.com/timnovinger
  16
+ *
8 17
  * Copyright (c) 2011 Scott Robbin (srobbin.com)
9 18
  * Dual licensed under the MIT and GPL licenses.
10 19
 */
11 20
 
12  
-;(function($) {
  21
+(function($) {
13 22
 
14 23
     $.backstretch = function(src, options, callback) {
15 24
         var defaultSettings = {
16  
-            centeredX: true,         // Should we center the image on the X axis?
17  
-            centeredY: true,         // Should we center the image on the Y axis?
18  
-            speed: 0                 // fadeIn speed for background after image loads (e.g. "fast" or 500)
  25
+            target: 'body',              // Apply on BODY by default or on a passed in element ID
  26
+            injectUsingPrepend: false,   // Append by default or prepend by passing in TRUE
  27
+            positionType: 'fixed',       // Normal CSS position types of relative, fixed, absolute
  28
+            centeredX: true,             // Should we center the image on the X axis?
  29
+            centeredY: true,             // Should we center the image on the Y axis?
  30
+            zIndex: '-999999',           // Option to pass in z-index value, if backstretch is being applied to a normal DIV this can be useful
  31
+            speed: 0                     // fadeIn speed for background after image loads (e.g. "fast" or 500)
19 32
         },
20  
-        container = $("#backstretch"),
21  
-        settings = container.data("settings") || defaultSettings, // If this has been called once before, use the old settings as the default
  33
+        container        = $(".backstretch"),
  34
+        settings         = container.data("settings") || defaultSettings, // If this has been called once before, use the old settings as the default
22 35
         existingSettings = container.data('settings'),
23  
-        rootElement = ("onorientationchange" in window) ? $(document) : $(window), // hack to acccount for iOS position:fixed shortcomings
24 36
         imgRatio, bgImg, bgWidth, bgHeight, bgOffset, bgCSS;
25  
-                
  37
+
26 38
         // Extend the settings with those the user has provided
27 39
         if(options && typeof options == "object") $.extend(settings, options);
28  
-        
29  
-        // Just in case the user passed in a function without options
30  
-        if(options && typeof options == "function") callback = options;
31  
-    
  40
+
  41
+        if (settings.target == 'body'){
  42
+          // hack to acccount for iOS position:fixed shortcomings
  43
+          rootElement = ("onorientationchange" in window) ? $(document) : $(window);
  44
+        } else {
  45
+          rootElement = $(settings.target);
  46
+        }
  47
+
32 48
         // Initialize
33 49
         $(document).ready(_init);
34  
-  
  50
+
35 51
         // For chaining
36 52
         return this;
37  
-    
  53
+
38 54
         function _init() {
39  
-            // Prepend image, wrapped in a DIV, with some positioning and zIndex voodoo
  55
+            // Inject image, wrapped in a DIV, with some positioning and zIndex voodoo
40 56
             if(src) {
41 57
                 var img;
42  
-                
  58
+
43 59
                 // If this is the first time that backstretch is being called
44 60
                 if(container.length == 0) {
45  
-                    container = $("<div />").attr("id", "backstretch")
46  
-                                            .css({left: 0, top: 0, position: "fixed", overflow: "hidden", zIndex: -999999, margin: 0, padding: 0, height: "100%", width: "100%"});
  61
+                    container = $("<div />").attr("class", "backstretch")
  62
+                                            .css({left: 0, top: 0, position: settings.positionType, overflow: "hidden", zIndex: settings.zIndex, margin: 0, padding: 0, height: "100%", width: "100%"});
47 63
                 } else {
48 64
                     // Prepare to delete any old images
49 65
                     container.find("img").addClass("deleteable");
50 66
                 }
51  
-                
52  
-                img = $("<img />").css({position: "absolute", display: "none", margin: 0, padding: 0, border: "none", zIndex: -999999})
53  
-                                  .bind("load", function(e) {                                          
  67
+
  68
+                img = $("<img />").css({position: "absolute", display: "none", margin: 0, padding: 0, border: "none", zIndex: settings.zIndex})
  69
+                                  .bind("load", function(e) {
54 70
                                       var self = $(this),
55 71
                                           imgWidth, imgHeight;
56  
-                                          
  72
+
57 73
                                       self.css({width: "auto", height: "auto"});
58 74
                                       imgWidth = this.width || $(e.target).width();
59 75
                                       imgHeight = this.height || $(e.target).height();
@@ -67,30 +83,33 @@
67 83
                                               if(typeof callback == "function") callback();
68 84
                                           });
69 85
                                       });
70  
-                                      
  86
+
71 87
                                   })
72 88
                                   .appendTo(container);
73  
-                 
  89
+
74 90
                 // Append the container to the body, if it's not already there
75  
-                if($("body #backstretch").length == 0) {
76  
-                    $("body").append(container);
  91
+                var $target        = $(settings.target),
  92
+                    injection_type = settings.injectUsingPrepend ? 'prepend' : 'append';
  93
+
  94
+                if($target.is('*') && $target.find('.backstretch').length == 0) {
  95
+                    $target[injection_type](container);
77 96
                 }
78  
-                
  97
+
79 98
                 // Attach the settings
80 99
                 container.data("settings", settings);
81  
-                    
  100
+
82 101
                 img.attr("src", src); // Hack for IE img onload event
83 102
                 // Adjust the background size when the window is resized or orientation has changed (iOS)
84 103
                 $(window).resize(_adjustBG);
85 104
             }
86 105
         }
87  
-            
  106
+
88 107
         function _adjustBG(fn) {
89 108
             try {
90 109
                 bgCSS = {left: 0, top: 0}
91 110
                 bgWidth = rootElement.width();
92 111
                 bgHeight = bgWidth / imgRatio;
93  
-                
  112
+
94 113
                 // Make adjustments based on image ratio
95 114
                 // Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
96 115
                 if(bgHeight >= rootElement.height()) {
@@ -103,16 +122,16 @@
103 122
                     if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
104 123
                 }
105 124
 
106  
-                $("#backstretch, #backstretch img:not(.deleteable)").width( bgWidth ).height( bgHeight )
107  
-                                                   .filter("img").css(bgCSS);
  125
+                $(".backstretch, .backstretch img:last").width( bgWidth ).height( bgHeight )
  126
+                                                        .filter("img").css(bgCSS);
108 127
             } catch(err) {
109 128
                 // IE7 seems to trigger _adjustBG before the image is loaded.
110 129
                 // This try/catch block is a hack to let it fail gracefully.
111 130
             }
112  
-      
  131
+
113 132
             // Executed the passed in function, if necessary
114 133
             if (typeof fn == "function") fn();
115 134
         }
116 135
     };
117  
-  
  136
+
118 137
 })(jQuery);
13  jquery.backstretch.min.js
... ...
@@ -1,11 +1,20 @@
1 1
 /*
2 2
  * jQuery Backstretch
3  
- * Version 1.2.5
  3
+ * Version 1.3
4 4
  * http://srobbin.com/jquery-plugins/jquery-backstretch/
  5
+ * http://github.com/colorjar/jquery-backstretch/
5 6
  *
6 7
  * Add a dynamically-resized background image to the page
7 8
  *
  9
+ * This is a fork of SRobbin's original 1.2.2 script.
  10
+ * It includes additional options and the ability to apply
  11
+ * the backstretch to multiple DIV containers, instead of
  12
+ * only the BODY of a page.
  13
+ *
  14
+ * ColorJar Author
  15
+ * Tim Novinger | http://github.com/timnovinger
  16
+ *
8 17
  * Copyright (c) 2011 Scott Robbin (srobbin.com)
9 18
  * Dual licensed under the MIT and GPL licenses.
10 19
 */
11  
-;(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);
  20
+(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)
Commit_comment_tip

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.