First, create the fixed header element using CSS. This can be done by setting the position property to "fixed", as well as defining the height and width of the element.
Set the background color of the fixed header element to the desired starting color using the background-color property.
Use JavaScript to detect when the page is scrolled. This can be done using the window.scrollY property which returns the number of pixels by which the document is currently scrolled vertically.
When the page is scrolled, use JavaScript to check the value of window.scrollY. If the value is greater than a certain threshold, set the background color of the fixed header element to a different color using the style.backgroundColor property.
To add a smooth transition effect, use CSS to set a transition property for the background-color property of the fixed header element. This will make the color change gradually instead of abruptly.
Here is an example of the CSS code:
.fixed-header { position: fixed; height: 60px; width: 100%; background-color: #FFFFFF; transition: background-color 0.5s ease; }
And here is an example of the JavaScript code:
window.addEventListener('scroll', function() { var scrollPosition = window.scrollY; if (scrollPosition > 100) { document.querySelector('.fixed-header').style.backgroundColor = '#000000'; } else { document.querySelector('.fixed-header').style.backgroundColor = '#FFFFFF'; } });
In this example, the header background color will change from white to black when the user scrolls beyond 100 pixels on the page.
Asked: 2021-12-26 11:00:00 +0000
Seen: 14 times
Last updated: Jun 17 '22