fixed-header-spacing.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. content.style.marginTop = header.offsetHeight + "px";
  43. if ( document.documentElement.clientHeight / 5 - header.offsetHeight >= 0 ) {
  44. body.classList.add( 'wp-sticky-header' );
  45. } else {
  46. body.classList.remove( 'wp-sticky-header' );
  47. }
  48. }
  49. };
  50. /**
  51. * Run our function every time the window resizes
  52. */
  53. var isResizing = false;
  54. window.addEventListener( 'resize',
  55. debounce( function() {
  56. if ( isResizing ) {
  57. return;
  58. }
  59. isResizing = true;
  60. setTimeout( function() {
  61. pageHeaderHeight();
  62. isResizing = false;
  63. }, 150 );
  64. } )
  65. );
  66. /**
  67. * Run our page header height function
  68. */
  69. pageHeaderHeight();
  70. })();