PageSourceSearch

https://ihcus.com/_javascript/jquery.backstretch.js

js ihcus.com collected 2026-10-06 19:07:59 UTC 12,960 bytes, 380 lines download raw bytes

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