1 | (function ($) {
|
2 |
|
3 | $.fn.parallax = function () {
|
4 | var window_width = $(window).width();
|
5 |
|
6 | return this.each(function(i) {
|
7 | var $this = $(this);
|
8 | $this.addClass('parallax');
|
9 |
|
10 | function updateParallax(initial) {
|
11 | var container_height;
|
12 | if (window_width < 601) {
|
13 | container_height = ($this.height() > 0) ? $this.height() : $this.children("img").height();
|
14 | }
|
15 | else {
|
16 | container_height = ($this.height() > 0) ? $this.height() : 500;
|
17 | }
|
18 | var $img = $this.children("img").first();
|
19 | var img_height = $img.height();
|
20 | var parallax_dist = img_height - container_height;
|
21 | var bottom = $this.offset().top + container_height;
|
22 | var top = $this.offset().top;
|
23 | var scrollTop = $(window).scrollTop();
|
24 | var windowHeight = window.innerHeight;
|
25 | var windowBottom = scrollTop + windowHeight;
|
26 | var percentScrolled = (windowBottom - top) / (container_height + windowHeight);
|
27 | var parallax = Math.round((parallax_dist * percentScrolled));
|
28 |
|
29 | if (initial) {
|
30 | $img.css('display', 'block');
|
31 | }
|
32 | if ((bottom > scrollTop) && (top < (scrollTop + windowHeight))) {
|
33 | $img.css('transform', "translate3D(-50%," + parallax + "px, 0)");
|
34 | }
|
35 |
|
36 | }
|
37 |
|
38 |
|
39 | $this.children("img").one("load", function() {
|
40 | updateParallax(true);
|
41 | }).each(function() {
|
42 | if (this.complete) $(this).trigger("load");
|
43 | });
|
44 |
|
45 | $(window).scroll(function() {
|
46 | window_width = $(window).width();
|
47 | updateParallax(false);
|
48 | });
|
49 |
|
50 | $(window).resize(function() {
|
51 | window_width = $(window).width();
|
52 | updateParallax(false);
|
53 | });
|
54 |
|
55 | });
|
56 |
|
57 | };
|
58 | }( jQuery ));
|