DEV Community

Cover image for Change Header Color when Scroll your page.
Luca
Luca

Posted on

6 3

Change Header Color when Scroll your page.

Hi Dev friends!
πŸ™‹

I want to write a small tutorial trick for change color of your fixed header when scroll your HTML page: it's simple and it's a nice view!

HTML: πŸ“–

First of all create your classic header section:


<header>
   <div id="container-header">
      <h1> THIS IS MY HEADER </h1>
   </div>
</header>

<main>
   <div id="container-main">
     <h1> THIS IS MY BODY </h1>
   </div>
</main>

Enter fullscreen mode Exit fullscreen mode

CSS: πŸ’…

Create your style, and add a class (in this case ".change-color", and i added a border bottom) for change color of your header when will scroll the page.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Header */

#container-header {
    height: 70px;
    width: 100vw;
    position: fixed;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #FFFFFF;
}

/* Add this class when scroll page */

.change-color {
    border-bottom: 0.5px solid #EDEDED;
}

/* Main */

#container-main {
    width: 100vw;
    height: 1100px;
    background-color: #000000;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #FFFFFF;
}


Enter fullscreen mode Exit fullscreen mode

jQuery: πŸ•Ί

Activate your class when scroll the page when is > 30, and remove this when is < 30.

$(document).on('scroll', function(){
    if ( $(window).scrollTop() > 30) {
        $('#container-header').addClass('change-color');
    } else {
        $('#container-header').removeClass('change-color');
    }
});

Enter fullscreen mode Exit fullscreen mode

Thank's for reading!

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay