PageSourceSearch

https://profkvdominic.com/js/jquery.backstretch.js

js profkvdominic.com collected 2026-10-02 14:01:18 UTC 11,741 bytes, 361 lines download raw bytes

1/*
2 * Backstretch
3 * http://srobbin.com/jquery-plugins/backstretch/
4 *
5 * Copyright (c) 2012 Scott Robbin
6 * Licensed under the MIT license.
7 */
8
9;(function ($, window, undefined) {
10  'use strict';
11
12  /* PLUGIN DEFINITION
13   * ========================= */
14
15  $.fn.backstretch = function (images, options) {
16    // We need at least one image
17    if (images === undefined || images.length === 0) {
18      $.error("No images were supplied for Backstretch");
19    }
20
21    /*
22     * Scroll the page one pixel to get the right window height on iOS
23     * Pretty harmless for everyone else
24    */
25    if ($(window).scrollTop() === 0 ) {
26      window.scrollTo(0, 0);
27    }
28
29    return this.each(function () {
30      var $this = $(this)
31        , obj = $this.data('backstretch');
32
33      // If we've already attached Backstretch to this element, remove the old instance.
34      if (obj) {
35        // Merge the old options with the new
36        options = $.extend(obj.options, options);
37
38        // Remove the old instance
39        obj.destroy(true);
40      }
41
42      obj = new Backstretch(this, images, options);
43      $this.data('backstretch', obj);
44    });
45  };
46
47  // If no element is supplied, we'll attach to body
48  $.backstretch = function (images, options) {
49    // Return the instance
50    return $('body')
51            .backstretch(images, options)
52            .data('backstretch');
53  };
54
55  // Custom selector
56  $.expr[':'].backstretch = function(elem) {
57    return $(elem).data('backstretch') !== undefined;
58  };
59
60  /* DEFAULTS
61   * ========================= */
62
63  $.fn.backstretch.defaults = {
64      centeredX: true   // Should we center the image on the X axis?
65    , centeredY: true   // Should we center the image on the Y axis?
66    , duration: 5000    // Amount of time in between slides (if slideshow)
67    , fade: 0           // Speed of fade transition between slides
68  };
69
70  /* STYLES
71   * 
72   * Baked-in styles that we'll apply to our elements.
73   * In an effort to keep the plugin simple, these are not exposed as options.
74   * That said, anyone can override these in their own stylesheet.
75   * ========================= */
76  var styles = {
77      wrap: {
78          left: 0
79        , top: 0
80        , overflow: 'hidden'
81        , margin: 0
82        , padding: 0
83        , height: '100%'
84        , width: '100%'
85        , zIndex: -999999
86      }
87    , img: {
88          position: 'absolute'
89        , display: 'none'
90        , margin: 0
91        , padding: 0
92        , border: 'none'
93        , width: 'auto'
94        , height: 'auto'
95        , maxWidth: 'none'
96        , zIndex: -999999
97      }
98  };
99
100  /* CLASS DEFINITION
101   * ========================= */
102  var Backstretch = function (container, images, options) {
103    this.options = $.extend({}, $.fn.backstretch.defaults, options || {});
104
105    /* In its simplest form, we allow Backstretch to be called on an image path.
106     * e.g. $.backstretch('/path/to/image.jpg')
107     * So, we need to turn this back into an array.
108     */
109    this.images = $.isArray(images) ? images : [images];
110
111    // Preload images
112    $.each(this.images, function () {
113      $('<img />')[0].src = this;
114    });    
115
116    // Convenience reference to know if the container is body.
117    this.isBody = container === document.body;
118
119    /* We're keeping track of a few different elements
120     *
121     * Container: the element that Backstretch was called on.
122     * Wrap: a DIV that we place the image into, so we can hide the overflow.
123     * Root: Convenience reference to help calculate the correct height.
124     */
125    this.$container = $(container);
126    this.$wrap = $('<div class="backstretch"></div>').css(styles.wrap).appendTo(this.$container);
127    this.$root = this.isBody ? supportsFixedPosition ? $(window) : $(document) : this.$container;
128
129    // Non-body elements need some style adjustments
130    if (!this.isBody) {
131      // If the container is statically positioned, we need to make it relative,
132      // and if no zIndex is defined, we should set it to zero.
133      var position = this.$container.css('position')
134        , zIndex = this.$container.css('zIndex');
135
136      this.$container.css({
137          position: position === 'static' ? 'relative' : position
138        , zIndex: zIndex === 'auto' ? 0 : zIndex
139        , background: 'none'
140      });
141      
142      // Needs a higher z-index
143      this.$wrap.css({zIndex: -999998});
144    }
145
146    // Fixed or absolute positioning?
147    this.$wrap.css({
148      position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute'
149    });
150
151    // Set the first image
152    this.index = 0;
153    this.show(this.index);
154
155    // Listen for resize
156    $(window).on('resize.backstretch', $.proxy(this.resize, this))
157             .on('orientationchange.backstretch', $.proxy(function () {
158                // Need to do this in order to get the right window height
159                if (this.isBody && window.pageYOffset === 0) {
160                  window.scrollTo(0, 1);
161                  this.resize();
162                }
163             }, this));
164  };
165
166  /* PUBLIC METHODS
167   * ========================= */
168  Backstretch.prototype = {
169      resize: function () {
170        try {
171          var bgCSS = {left: 0, top: 0}
172            , rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth()
173            , bgWidth = rootWidth
174            , rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHe
174ight()
175            , bgHeight = bgWidth / this.$img.data('ratio')
176            , bgOffset;
177
178            // Make adjustments based on image ratio
179            if (bgHeight >= rootHeight) {
180                bgOffset = (bgHeight - rootHeight) / 2;
181                if(this.options.centeredY) {
182                  bgCSS.top = '-' + bgOffset + 'px';
183                }
184            } else {
185                bgHeight = rootHeight;
186                bgWidth = bgHeight * this.$img.data('ratio');
187                bgOffset = (bgWidth - rootWidth) / 2;
188                if(this.options.centeredX) {
189                  bgCSS.left = '-' + bgOffset + 'px';
190                }
191            }
192
193            this.$wrap.css({width: rootWidth, height: rootHeight})
194                      .find('img:not(.deleteable)').css({width: bgWidth, height: bgHeight}).css(bgCSS);
195        } catch(err) {
196            // IE7 seems to trigger resize before the image is loaded.
197            // This try/catch block is a hack to let it fail gracefully.
198        }
199
200        return this;
201      }
202
203      // Show the slide at a certain position
204    , show: function (index) {
205        // Validate index
206        if (Math.abs(index) > this.images.length - 1) {
207          return;
208        } else {
209          this.index = index;
210        }
211
212        // Vars
213        var self = this
214          , oldImage = self.$wrap.find('img').addClass('deleteable')
215          , evt = $.Event('backstretch.show', {
216              relatedTarget: self.$container[0]
217            });
218
219        // Pause the slideshow
220        clearInterval(self.interval);
221
222        // New image
223        self.$img = $('<img />')
224                      .css(styles.img)
225                      .bind('load', function (e) {
226                        var imgWidth = this.width || $(e.target).width()
227                          , imgHeight = this.height || $(e.target).height();
228                        
229                        // Save the ratio
230                        $(this).data('ratio', imgWidth / imgHeight);
231
232                        // Resize
233                        self.resize();
234
235                        // Show the image, then delete the old one
236                        // "speed" option has been deprecated, but we want backwards compatibilty
237                        $(this).fadeIn(self.options.speed || self.options.fade, function () {
238                          oldImage.remove();
239
240                          // Resume the slideshow
241                          if (!self.paused) {
242                            self.cycle();
243                          }
244
245                          // Trigger the event
246                          self.$container.trigger(evt);
247                        });
248                      })
249                      .appendTo(self.$wrap);
250
251        // Hack for IE img onload event
252        self.$img.attr('src', self.images[index]);
253        return self;
254      }
255
256    , next: function () {
257        // Next slide
258        return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0);
259      }
260
261    , prev: function () {
262        // Previous slide
263        return this.show(this.index === 0 ? this.images.length - 1 : this.index - 1);
264      }
265
266    , pause: function () {
267        // Pause the slideshow
268        this.paused = true;
269        return this;
270      }
271
272    , resume: function () {
273        // Resume the slideshow
274        this.paused = false;
275        this.next();
276        return this;
277      }
278
279    , cycle: function () {
280        // Start/resume the slideshow
281        if(this.images.length > 1) {
282          // Clear the interval, just in case
283          clearInterval(this.interval);
284
285          this.interval = setInterval($.proxy(function () {
286            // Check for paused slideshow
287            if (!this.paused) {
288              this.next();
289            }
290          }, this), this.options.duration);
291        }
292        return this;
293      }
294
vendor: 2,463 bytes, lines 295-361
295    , destroy: function (preserveBackground) {
296        // Stop the resize events
297        $(window).off('resize.backstretch orientationchange.backstretch');
298
299        // Clear the interval
300        clearInterval(this.interval);
301
302        // Remove Backstretch
303        if(!preserveBackground) {
304          this.$wrap.remove();          
305        }
306        this.$container.removeData('backstretch');
307      }
308  };
309
310  /* SUPPORTS FIXED POSITION?
311   *
312   * Based on code from jQuery Mobile 1.1.0
313   * http://jquerymobile.com/
314   *
315   * In a nutshell, we need to figure out if fixed positioning is supported.
316   * Unfortunately, this is very difficult to do on iOS, and usually involves
317   * injecting content, scrolling the page, etc.. It's ugly.
318   * jQuery Mobile uses this workaround. It's not ideal, but works.
319   *
320   * Modified to detect IE6
321   * ========================= */
322
323  var supportsFixedPosition = (function () {
324    var ua = navigator.userAgent
325      , platform = navigator.platform
326        // Rendering engine is Webkit, and capture major version
327      , wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ )
328      , wkversion = !!wkmatch && wkmatch[ 1 ]
329      , ffmatch = ua.match( /Fennec\/([0-9]+)/ )
330      , ffversion = !!ffmatch && ffmatch[ 1 ]
331      , operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ )
332      , omversion = !!operammobilematch && operammobilematch[ 1 ]
333      , iematch = ua.match( /MSIE ([0-9]+)/ )
334      , ieversion = !!iematch && iematch[ 1 ];
335
336    return !(
337      // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
338      ((platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1  || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534) ||
339      
340      // Opera Mini
341      (window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]") ||
342      (operammobilematch && omversion < 7458) ||
343      
344      //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
345      (ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533) ||
346      
347      // Firefox Mobile before 6.0 -
348      (ffversion && ffversion < 6) ||
349      
350      // WebOS less than 3
351      ("palmGetResource" in window && wkversion && wkversion < 534) ||
352      
353      // MeeGo
354      (ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1) ||
355      
356      // IE6
357      (ieversion && ieversion <= 6)
358    );
359  }());
360
361}(jQuery, window));

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.