You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
2.2 KiB

2 years ago
  1. (function ($) {
  2. $.fn.stickySidebar = function (options) {
  3. var config = $.extend({
  4. headerSelector: 'header',
  5. navSelector: '#menuWrapper',
  6. contentSelector: '#left',
  7. footerSelector: '#footer',
  8. sidebarTopMargin: 25,
  9. footerThreshold: 100
  10. }, options);
  11. var fixSidebr = function () {
  12. var sidebarSelector = $(this);
  13. var viewportHeight = $(window).height();
  14. var viewportWidth = $(window).width();
  15. var documentHeight = $(document).height();
  16. var headerHeight = $(config.headerSelector).outerHeight();
  17. var navHeight = $(config.navSelector).outerHeight();
  18. var sidebarHeight = sidebarSelector.outerHeight();
  19. var contentHeight = $(config.contentSelector).outerHeight();
  20. var footerHeight = $(config.footerSelector).outerHeight();
  21. var scroll_top = $(window).scrollTop();
  22. var fixPosition = contentHeight - sidebarHeight;
  23. //var breakingPoint1 = headerHeight
  24. var breakingPoint1 = headerHeight + navHeight;
  25. var breakingPoint2 = documentHeight - (sidebarHeight + footerHeight + config.footerThreshold);
  26. // calculate
  27. if ((contentHeight > sidebarHeight) && (viewportHeight > sidebarHeight)) {
  28. if (scroll_top < breakingPoint1) {
  29. sidebarSelector.removeClass('sticky');
  30. } else if ((scroll_top >= breakingPoint1) && (scroll_top < breakingPoint2)) {
  31. sidebarSelector.addClass('sticky').css('top', config.sidebarTopMargin);
  32. } else {
  33. var negative = breakingPoint2 - scroll_top;
  34. sidebarSelector.addClass('sticky').css('top', negative);
  35. }
  36. }
  37. };
  38. return this.each(function () {
  39. $(window).on('scroll', $.proxy(fixSidebr, this));
  40. $(window).on('resize', $.proxy(fixSidebr, this))
  41. $.proxy(fixSidebr, this)();
  42. });
  43. };
  44. }(jQuery));
  45. $(document).ready(function () {
  46. $('#sidebar').stickySidebar({
  47. //sidebarTopMargin: 70,
  48. //footerThreshold: 100
  49. });
  50. });