dynamiccolor.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. (function($) {
  2. "use strict";
  3. window.mkdf = {};
  4. mkdf.scroll = 0;
  5. mkdf.body = $('body');
  6. mkdf.windowHeight = $(window).height();
  7. var common = {};
  8. common.mkdfOnDocumentReady = mkdfOnDocumentReady;
  9. /*
  10. * Init Element in View
  11. */
  12. function mkdfElementInView(element) {
  13. $(window).scroll(function() {
  14. if (mkdf.scroll > element.offset().top - mkdf.windowHeight && mkdf.scroll < element.offset().top + element.height()) {
  15. if (!element.hasClass('mkdf-in-view')) {
  16. element.addClass('mkdf-in-view');
  17. }
  18. } else {
  19. if (element.hasClass('mkdf-in-view')) {
  20. element.removeClass('mkdf-in-view');
  21. }
  22. }
  23. });
  24. }
  25. /**
  26. * Dynamic Background Color
  27. */
  28. function mkdfDynamicBackgroundColor() {
  29. var bgrndIntances = $("[data-dynamic-bgrnd]");
  30. if (mkdf.body.hasClass('mkdf-dynamic-background-color') && bgrndIntances.length) {
  31. $('.main-content').append('<div id="mkdf-dynamic-bgrnds"></div');
  32. var holder = $('#mkdf-dynamic-bgrnds'),
  33. scrollBuffer = mkdf.scroll,
  34. scrollingDown = true,
  35. currentScroll, instancesInView, activeEl;
  36. //add bgrnd divs
  37. bgrndIntances.each(function() {
  38. mkdfElementInView($(this));
  39. });
  40. //calculate scroll direction
  41. var scrollDirection = function() {
  42. currentScroll = mkdf.scroll;
  43. if (currentScroll > scrollBuffer) {
  44. scrollingDown = true;
  45. } else {
  46. scrollingDown = false;
  47. }
  48. scrollBuffer = currentScroll;
  49. };
  50. holder.css('background-color', bgrndIntances.first().attr('data-dynamic-bgrnd'));
  51. //colors change logic
  52. $(window).on('scroll', function() {
  53. scrollDirection();
  54. instancesInView = bgrndIntances.filter('.mkdf-in-view');
  55. if (instancesInView.length) {
  56. if (scrollingDown) {
  57. activeEl = instancesInView.last();
  58. } else {
  59. activeEl = instancesInView.first();
  60. }
  61. holder.css('background-color') !== activeEl.attr('data-dynamic-bgrnd') &&
  62. holder.css('background-color', activeEl.attr('data-dynamic-bgrnd'));
  63. }
  64. });
  65. }
  66. }
  67. function mkdfOnDocumentReady() {
  68. mkdfDynamicBackgroundColor();
  69. }
  70. $(document).ready(mkdfOnDocumentReady);
  71. })(jQuery);