简体   繁体   中英

Change header background after the user scrolls

I've been googling about this and came across this solution:

$(function() {
    $(window).on("scroll", function() {
        if($(window).scrollTop() > 50) {
            $(".header").addClass("active");
        } else {
            //remove the background property so it comes transparent again
           $(".header").removeClass("active");
        }
    });
});

Here's the CSS:

header{
    display: flex;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: transparent;
    height: 70px;
    align-items: center;
    justify-content: space-between;
}

.active{
    background-color: lightgray;
}

And the HTML:

<body>

    <header>

        <a href="#" class="logo">
            <h3>
                Logo will go here
            </h3>
        </a>

        <div class="header-links">
            <a id="home-link" href="#home">Home</a>
            <a id="portfolio-link" href="#portfolio">Portfolio</a>
            <a id="about-link" href="#about">About me</a>
            <a id="contact-link" href="#contact">Contact</a>
        </div>

    </header>

And at the end of the body in my html is:

    <script src="{{ asset('js/script.js') }}"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</body>

The browser Dev Tools console show this error 3 times:

Uncaught ReferenceError: $ is not defined

What I need is for the Header to change into a new background color after the user scrolls the screen down some pixels. I serached online and mostly found the same fix which is this presented above, but for some reason it just don't work, my header never changes the background color. Any ideas why?

If asset('js/script.js') is where you keep your $(function () {... }) code, then it should be loaded after jquery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{{ asset('js/script.js') }}"></script>

I tried this code and it worked for me. The problem was the css.

$(window).on("scroll", function() {
    if($(window).scrollTop() > 50) {
        $(".header").addClass("active");
    } else {
       //remove the background property so it comes transparent again
       $(".header").removeClass("active");
    }
});

Add !important to your.active class and it should work.

.active{
    background-color: lightgray !important;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM