Skip to content
Advertisement

How to get a Sticky header on website using Javascript?

Tried to get a sticky header onto my website using javascript, but doesn’t seem to be working.

Here is the html code and javascript related to this section:

<header>
    <a href="#" class="logo">Food<span>.</span></a>
    <ul class="navigation">
        <li><a href="#banner">Home</a></li>
        <li><a href="#about">About</a></li>
        <li><a href="#menu">Menu</a></li>
        <li><a href="#expert">Expert</a></li>
        <li><a href="#testimonials">Testimonials</a></li>
        <li><a href="#contact">Contact</a></li>
    </ul>
</header>

<script type="text/javascript">
    window.addEventListener('scroll', function () {
        const header = document.querySelector('header');
        header.classList.toggle("sticky", window.scrollY > 0);
    });
</script>

Here is the CSS related to the sticky header:

header .sticky {
background: #fff;
padding: 10px 100px;
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

header .sticky .logo {
color: #111;
}

header .sticky .navigation li a {
color: #111;
}

Please help!

Answer

Step 1. Use header.sticky instead of header .sticky (remove space)

Step 2. Add the following style to header.sticky

position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;

How TO – Sticky Element

Advertisement