fixed-header-spacing.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. (function() {
  2. /**
  3. * Debounce
  4. *
  5. * @param {Function} func
  6. * @param {number} wait
  7. * @param {boolean} immediate
  8. */
  9. function debounce(func, wait, immediate) {
  10. 'use strict';
  11. var timeout;
  12. wait = (typeof wait !== 'undefined') ? wait : 20;
  13. immediate = (typeof immediate !== 'undefined') ? immediate : true;
  14. return function() {
  15. var context = this, args = arguments;
  16. var later = function() {
  17. timeout = null;
  18. if (!immediate) {
  19. func.apply(context, args);
  20. }
  21. };
  22. var callNow = immediate && !timeout;
  23. clearTimeout(timeout);
  24. timeout = setTimeout(later, wait);
  25. if (callNow) {
  26. func.apply(context, args);
  27. }
  28. };
  29. }
  30. /**
  31. * Get page header height and use it for top-margin on
  32. * site-content when above mobile breakpoint
  33. */
  34. function pageHeaderHeight() {
  35. var body = document.body;
  36. if ( document.documentElement.clientWidth <= 640 ) {
  37. document.getElementById( "primary" ).style.marginTop = 0;
  38. body.classList.remove( 'wp-sticky-header' );
  39. } else {
  40. var header = document.getElementById( 'masthead' );
  41. var content = document.getElementById( 'primary' );
  42. var headerOffsetHeight = 0;
  43. if ( header ) {
  44. headerOffsetHeight = header.offsetHeight;
  45. content.style.marginTop = headerOffsetHeight + "px";
  46. }
  47. if ( document.documentElement.clientHeight / 5 - headerOffsetHeight >= 0 ) {
  48. body.classList.add( 'wp-sticky-header' );
  49. } else {
  50. body.classList.remove( 'wp-sticky-header' );
  51. }
  52. }
  53. };
  54. /**
  55. * Run our function every time the window resizes
  56. */
  57. var isResizing = false;
  58. window.addEventListener( 'resize',
  59. debounce( function() {
  60. if ( isResizing ) {
  61. return;
  62. }
  63. isResizing = true;
  64. setTimeout( function() {
  65. pageHeaderHeight();
  66. isResizing = false;
  67. }, 150 );
  68. } )
  69. );
  70. /**
  71. * Run our page header height function
  72. */
  73. window.addEventListener( 'load', pageHeaderHeight );
  74. pageHeaderHeight();
  75. })();