Udoro

Header auto Background change JS

Jun 18th, 2025 (edited)
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.19 KB | None | 0 0
  1. // Constants
  2. const BREAKPOINT_DESKTOP = MegaMenuCONFIG.minWidth;
  3. const DEBOUNCE_DELAY = 100;
  4.  
  5. // Configuration object for all header-related selectors
  6. const HEADER_CONFIG = {
  7. // Main header element
  8. headerElement: '.dwc-nest-header',
  9. // Wrapper element (try class first, then ID as fallback)
  10. wrapperElement: {
  11. class: '.dwc-nest-header__container-',
  12. id: 'brxe-8dc5d5'
  13. },
  14. // Logo element and its white variant class
  15. logo: {
  16. selector: '.dwc-nest-menu__logo svg',
  17. whiteClass: 'logo-svg-main--white'
  18. },
  19. // Hero section class
  20. heroSectionClass: 'hero-section', // Configurable hero section class
  21. // Store original header background color
  22. originalHeaderBgColor: null
  23. };
  24.  
  25. // Configuration for video sections
  26. const VIDEO_CONFIG = {
  27. // Class that identifies video sections
  28. sectionClass: 'hero-video',
  29. // Background color to apply to header when over video sections
  30. headerBgColor: 'transparent', // Change this to your desired color
  31. // Background class to apply to header when over video sections
  32. headerBgClass: 'bg--ultra-dark'
  33. };
  34.  
  35. // Text color classes
  36. const TEXT_CLASSES = {
  37. light: 'dwc-on-dark-bg',
  38. dark: 'dwc-on-light-bg'
  39. };
  40.  
  41. // Debounce function for performance optimization
  42. function debounce(func, wait) {
  43. let timeout;
  44. return function executedFunction(...args) {
  45. const later = () => {
  46. clearTimeout(timeout);
  47. func(...args);
  48. };
  49. clearTimeout(timeout);
  50. timeout = setTimeout(later, wait);
  51. };
  52. }
  53.  
  54. // Function to get computed background color of an element
  55. function getComputedBackgroundColor(element) {
  56. const computedStyle = window.getComputedStyle(element);
  57. let bgColor = computedStyle.backgroundColor;
  58.  
  59. // console.log('Element background color:', bgColor, 'for element:', element);
  60.  
  61. return bgColor;
  62. }
  63.  
  64. // Function to convert color to RGB values
  65. function getRGBValues(color) {
  66. // Create a temporary element to get computed color
  67. const temp = document.createElement('div');
  68. temp.style.color = color;
  69. document.body.appendChild(temp);
  70. const computedColor = window.getComputedStyle(temp).color;
  71. document.body.removeChild(temp);
  72.  
  73. // Extract RGB values
  74. const match = computedColor.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
  75. if (match) {
  76. return {
  77. r: parseInt(match[1]),
  78. g: parseInt(match[2]),
  79. b: parseInt(match[3])
  80. };
  81. }
  82.  
  83. // Fallback for rgba
  84. const rgbaMatch = computedColor.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*[\d.]+\)/);
  85. if (rgbaMatch) {
  86. return {
  87. r: parseInt(rgbaMatch[1]),
  88. g: parseInt(rgbaMatch[2]),
  89. b: parseInt(rgbaMatch[3])
  90. };
  91. }
  92.  
  93. return { r: 255, g: 255, b: 255 }; // Default to white
  94. }
  95.  
  96. // Function to determine if a color is dark or light
  97. function isColorDark(color) {
  98. if (color === 'transparent' || color === 'rgba(0, 0, 0, 0)') {
  99. return false; // Treat transparent as light
  100. }
  101.  
  102. const rgb = getRGBValues(color);
  103. // Calculate luminance using the standard formula
  104. const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
  105. return luminance < 0.5;
  106. }
  107.  
  108. // Function that detects which section is currently visible
  109. function getCurrentSection() {
  110. const headerElement = document.querySelector(HEADER_CONFIG.headerElement);
  111. if (!headerElement) return null;
  112.  
  113. const headerHeight = headerElement.offsetHeight;
  114. const sections = Array.from(document.querySelectorAll('section'));
  115.  
  116. for (const section of sections) {
  117. const rect = section.getBoundingClientRect();
  118. if (rect.top <= headerHeight && rect.bottom > headerHeight) {
  119. return section;
  120. }
  121. }
  122.  
  123. return sections[0] || null;
  124. }
  125.  
  126. // Function to initialize original header background color
  127. function initializeOriginalHeaderBgColor() {
  128. const headerElement = document.querySelector(HEADER_CONFIG.headerElement);
  129. if (headerElement) {
  130. HEADER_CONFIG.originalHeaderBgColor = window.getComputedStyle(headerElement).backgroundColor;
  131. // console.log('Original header background color:', HEADER_CONFIG.originalHeaderBgColor);
  132. }
  133. }
  134.  
  135. // Function to determine header style configuration based on section
  136. function determineHeaderConfig(section) {
  137. if (!section) return null;
  138.  
  139. // Check if it's a hero section
  140. const isHeroSection = section.classList.contains(HEADER_CONFIG.heroSectionClass);
  141.  
  142. // Check if it's a video section
  143. const isVideoSection = section.classList.contains(VIDEO_CONFIG.sectionClass);
  144.  
  145. if (isHeroSection) {
  146. return {
  147. backgroundColor: HEADER_CONFIG.originalHeaderBgColor || 'rgb(255, 255, 255)', // Fallback to white if not set
  148. bgClass: null,
  149. needsWhiteText: isColorDark(HEADER_CONFIG.originalHeaderBgColor || 'rgb(255, 255, 255)'),
  150. applyOverrideClass: false, // No override class for hero section
  151. applyHeroClass: true // Apply hero class for hero section
  152. };
  153. }
  154.  
  155. if (isVideoSection) {
  156. return {
  157. backgroundColor: VIDEO_CONFIG.headerBgColor,
  158. bgClass: VIDEO_CONFIG.headerBgClass,
  159. needsWhiteText: true, // Video sections typically need white text
  160. applyOverrideClass: true, // Apply override class for video section
  161. applyHeroClass: false // No hero class for video section
  162. };
  163. }
  164.  
  165. // Get the actual background color of the section
  166. const sectionBgColor = getComputedBackgroundColor(section);
  167. const needsWhiteText = isColorDark(sectionBgColor);
  168.  
  169. return {
  170. backgroundColor: sectionBgColor,
  171. bgClass: null, // We'll determine this based on the color
  172. needsWhiteText: needsWhiteText,
  173. applyOverrideClass: true, // Apply override class for other sections
  174. applyHeroClass: false // No hero class for other sections
  175. };
  176. }
  177.  
  178. // Function to get header elements
  179. function getHeaderElements() {
  180. const headerElement = document.querySelector(HEADER_CONFIG.headerElement);
  181.  
  182. // Try to find wrapper by class first, then ID
  183. let wrapperElement = document.querySelector(HEADER_CONFIG.wrapperElement.class);
  184. if (!wrapperElement) {
  185. wrapperElement = document.getElementById(HEADER_CONFIG.wrapperElement.id.replace('#', ''));
  186. }
  187.  
  188. const logo = document.querySelector(HEADER_CONFIG.logo.selector);
  189.  
  190. return { headerElement, wrapperElement, logo };
  191. }
  192.  
  193. // Function to apply styles to header elements
  194. function applyHeaderStyles(elements, config) {
  195. const { headerElement, wrapperElement, logo } = elements;
  196.  
  197. if (!headerElement || !config) return;
  198.  
  199. // Remove existing background classes that start with 'bg--'
  200. const elementsToStyle = [headerElement, wrapperElement].filter(Boolean);
  201.  
  202. elementsToStyle.forEach(element => {
  203. // Remove existing bg classes
  204. const classList = Array.from(element.classList);
  205. classList.forEach(cls => {
  206. if (cls.startsWith('bg--')) {
  207. element.classList.remove(cls);
  208. }
  209. });
  210.  
  211. // Remove existing text color classes
  212. element.classList.remove(TEXT_CLASSES.light, TEXT_CLASSES.dark);
  213.  
  214. // Remove bg-color-override and header-on-hero classes
  215. element.classList.remove('bg-color-override', 'header-on-hero');
  216.  
  217. // Apply background color, ensuring no transparency
  218. const appliedBgColor = config.backgroundColor || '';
  219. element.style.backgroundColor = appliedBgColor;
  220.  
  221. // Set CSS custom property for current background color
  222. element.style.setProperty('--var-current-header-bg', appliedBgColor);
  223.  
  224. // Apply background class if specified
  225. if (config.bgClass) {
  226. element.classList.add(config.bgClass);
  227. }
  228.  
  229. // Apply override class if specified
  230. if (config.applyOverrideClass) {
  231. element.classList.add('bg-color-override');
  232. }
  233.  
  234. // Apply hero class if specified
  235. if (config.applyHeroClass) {
  236. element.classList.add('header-on-hero');
  237. }
  238.  
  239. // Apply text color class
  240. if (config.needsWhiteText) {
  241. element.classList.add(TEXT_CLASSES.light);
  242. } else {
  243. element.classList.add(TEXT_CLASSES.dark);
  244. }
  245. });
  246.  
  247. // Handle logo color
  248. if (logo) {
  249. if (config.needsWhiteText) {
  250. logo.classList.add(HEADER_CONFIG.logo.whiteClass);
  251. } else {
  252. logo.classList.remove(HEADER_CONFIG.logo.whiteClass);
  253. }
  254. }
  255. }
  256.  
  257. // Main function to update header styles
  258. function updateHeaderStyles() {
  259. // Apply only on screens larger than the breakpoint
  260. if (window.innerWidth <= BREAKPOINT_DESKTOP) {
  261. // console.log('Window width is below breakpoint, skipping header update');
  262. return;
  263. }
  264.  
  265. const currentSection = getCurrentSection();
  266. if (!currentSection) {
  267. // console.log('No current section found');
  268. return;
  269. }
  270.  
  271. // console.log('Current section:', currentSection, 'Classes:', Array.from(currentSection.classList));
  272.  
  273. const headerConfig = determineHeaderConfig(currentSection);
  274. if (!headerConfig) {
  275. // console.log('No header config determined');
  276. return;
  277. }
  278.  
  279. // console.log('Header config:', headerConfig);
  280.  
  281. const headerElements = getHeaderElements();
  282. // console.log('Header elements found:', {
  283. // header: !!headerElements.headerElement,
  284. // wrapper: !!headerElements.wrapperElement,
  285. // logo: !!headerElements.logo
  286. // });
  287.  
  288. applyHeaderStyles(headerElements, headerConfig);
  289. // console.log('Header styles applied');
  290. }
  291.  
  292. // Initialize on page load
  293. initializeOriginalHeaderBgColor();
  294. updateHeaderStyles();
  295.  
  296. // Create debounced version for scroll and resize events
  297. const debouncedUpdateHeaderStyles = debounce(updateHeaderStyles, DEBOUNCE_DELAY);
  298.  
  299. // Add event listeners
  300. window.addEventListener('scroll', debouncedUpdateHeaderStyles);
  301. window.addEventListener('resize', debouncedUpdateHeaderStyles);
Advertisement
Add Comment
Please, Sign In to add comment