❤️🔥How to Create a header line that appears when a user scrolls using HTML, CSS, and JavaScript
Explain :
HTML:
We create a
div
element with a class ofheader-line
that will act as our header line.We also create a
div
with a class ofcontent
to contain enough text to make the page scrollable.
CSS:
We set up basic styling for the body and HTML to ensure the page has enough height and a sans-serif font.
The
.header-line
class styles the header line to be fixed at the top of the page, with an initial transform property to hide it above the viewport.A smooth transition is set for the transform property to allow the header line to slide down smoothly when the user scrolls.
JavaScript:
We add an event listener for the
scroll
event.In the event handler, we check the
scrollY
property (the number of pixels the document has already been scrolled vertically).If the
scrollY
value is greater than 50 pixels, we set thetransform
property of the header line totranslateY(0)
to slide it into view.If the
scrollY
value is 50 pixels or less, we hide the header line by setting thetransform
property back totranslateY(-100%)
.
Last updated