❤️🔥How to Create a header line that appears when a user scrolls using HTML, CSS, and JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body, html {
margin: 0;
padding: 0;
height: 200%;
font-family: Arial, sans-serif;
}
.header-line {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 4px;
background-color: blue;
transform: translateY(-100%);
transition: transform 0.3s ease;
}
.content {
padding: 20px;
}
</style>
</head>
<body>
<div class="header-line" id="headerLine"></div>
<div class="content">
<!-- Add lots of content here to enable scrolling -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vitae vehicula nunc, in consectetur libero. Nullam id tincidunt risus, eget venenatis lectus. Suspendisse potenti. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Vivamus auctor ligula nec turpis pharetra, in dignissim mauris tempus. Nam vitae ante volutpat, elementum lorem ut, posuere sem. Maecenas eget sem ultricies, consequat mi sed, commodo nisl.</p>
<!-- Repeat the paragraph above or add more content to allow scrolling -->
</div>
<script>
window.addEventListener('scroll', () => {
const headerLine = document.getElementById('headerLine');
if (window.scrollY > 50) {
headerLine.style.transform = 'translateY(0)';
} else {
headerLine.style.transform = 'translateY(-100%)';
}
});
</script>
</body>
</html>
Explain :
HTML:
We create a
divelement with a class ofheader-linethat will act as our header line.We also create a
divwith a class ofcontentto 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-lineclass 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
scrollevent.In the event handler, we check the
scrollYproperty (the number of pixels the document has already been scrolled vertically).If the
scrollYvalue is greater than 50 pixels, we set thetransformproperty of the header line totranslateY(0)to slide it into view.If the
scrollYvalue is 50 pixels or less, we hide the header line by setting thetransformproperty back totranslateY(-100%).
Last updated