jquery.parallax.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Plugin: jQuery Parallax
  3. Version 1.1.3
  4. Author: Ian Lunn
  5. Twitter: @IanLunn
  6. Author URL: http://www.ianlunn.co.uk/
  7. Plugin URL: http://www.ianlunn.co.uk/plugins/jquery-parallax/
  8. Dual licensed under the MIT and GPL licenses:
  9. http://www.opensource.org/licenses/mit-license.php
  10. http://www.gnu.org/licenses/gpl.html
  11. */
  12. (function( $ ){
  13. var $window = $(window);
  14. var windowHeight = $window.height();
  15. $window.resize(function () {
  16. windowHeight = $window.height();
  17. });
  18. $.fn.parallax = function(xpos, speedFactor, outerHeight) {
  19. var $this = $(this);
  20. var getHeight;
  21. var firstTop;
  22. var paddingTop = 0;
  23. //get the starting position of each element to have parallax applied to it
  24. function update (){
  25. $this.each(function(){
  26. firstTop = $this.offset().top;
  27. });
  28. if (outerHeight) {
  29. getHeight = function(jqo) {
  30. return jqo.outerHeight(true);
  31. };
  32. } else {
  33. getHeight = function(jqo) {
  34. return jqo.height();
  35. };
  36. }
  37. // setup defaults if arguments aren't specified
  38. if (arguments.length < 1 || xpos === null) xpos = "50%";
  39. if (arguments.length < 2 || speedFactor === null) speedFactor = 0.5;
  40. if (arguments.length < 3 || outerHeight === null) outerHeight = true;
  41. // function to be called whenever the window is scrolled or resized
  42. var pos = $window.scrollTop();
  43. $this.each(function(){
  44. var $element = $(this);
  45. var top = $element.offset().top;
  46. var height = getHeight($element);
  47. // Check if totally above or totally below viewport
  48. if (top + height < pos || top > pos + windowHeight) {
  49. return;
  50. }
  51. $this.css('backgroundPosition', xpos + " " + Math.round((firstTop - pos) * speedFactor) + "px");
  52. });
  53. }
  54. $window.bind('scroll', update).resize(update);
  55. update();
  56. };
  57. })(jQuery);