Tips for modifying navbar appearance as user scrolls?

I am currently working on a website using Bootstrap 4. The goal is to create a navbar with a transparent background that transitions to white smoothly when the user scrolls down. I want the navbar to return to its initial state when the user scrolls back up. A similar effect can be seen in the following example: https://www.w3schools.com/w3css/tryw3css_templates_parallax.htm

I attempted to achieve this effect using pure JavaScript, but the code did not work as expected.

Thank you in advance for any assistance!

JavaScript:

window.onscroll = function() {myFunction()};

function myFunction() {

    var navbarClass = document.getElementById("myNavbar").className.split(/\s+/);
    for (var i = 0; i < navbarClass.length; i++) {

        if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
            navbarClass[i].classList.add("border", "animate-top");
        } else if (navbarClass[i].classList.contains("nav")) {
            navbarClases[i].classList.toggle("nav-white");
        }
    }

}

CSS

.first > div {
    color: #fff;
}
section {
    height: 350px;   
}
.first {
    padding-top: 70px;
    background-image: url('https://picsum.photos/1920/1080/?random');
    height: auto;
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
.nav {
    border: 0;
    border-radius: 0;
    background: rgba(255, 255, 255, 0.5);
}
.nav-white {
    border: 0;
    border-radius: 0;
    background: rgba(255, 255, 255, 1);
}
.nav-white .navbar-brand {
    color: black;
}
.nav-white .navbar-nav li a {
    color: black;
}
.nav-white .fa.fa-navicon {
    color: black;
}
.border {
    box-shadow:0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12)
}
.animate-top{
    animation:animatetop 0.4s}@keyframes animatetop{from{top:-300px;opacity:0} to{top:0;opacity:1}
}

HTML NAVBAR

<nav class="navbar navbar-expand-lg fixed-top nav" id="myNavbar">
    <a href="#" class="navbar-brand">Menu</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Navigation Menu">
        <span class="navbar-toggler-icon">
            <i class="fa fa-navicon"></i>
        </span>
    </button>
    <div class="collapse navbar-collapse" id="navbar">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a href="#" class="nav-link">TITLE 1</a>
            </li>                   
            <li class="nav-item">
                <a href="#" class="nav-link">TITLE 2</a>
            </li>
            <li class="nav-item">
                <a href="#" class="nav-link">TITLE 3</a>
            </li>
        </ul>
    </div>
</nav>

HTML

<section class="first row">
    <div class="col">                
        <h2>MAIN</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>      
</section>    

<section class="row">
    <div class="col">
        <h2>TITLE 1</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
</section>

Answer №1

When working with Bootstrap, it's advantageous to make use of jQuery. This is how I implement it:

The jQuery script toggles the "scrolled" class based on the position, which then changes the color accordingly.

 $(document).scroll(function () {
    $(".fixed-top").toggleClass('scrolled', $(this).scrollTop() >  $(".fixed-top").height());
  });
.fixed-top.scrolled {
background-color:rgba(255,255,255,1) !important;
transition: background-color 200ms linear;
}

Answer №2

Everything looks good, but I noticed that the code is missing "position: fixed" which is necessary to keep the navbar fixed at the top of the screen.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Designing personalized sass components

Seeking advice on developing a custom CSS unit that can be utilized in Sass with Node.js. Is there a tutorial available for creating a Sass plugin specifically for this purpose? For instance, I am looking to establish a unit called "dpx" which functions as ...

Ways to enable automatic scrolling of a page as the content expands (Utilizing collapsible elements)

For a recent project I've been working on, I decided to include 4 collapsible text boxes. However, I encountered an issue where opening content1 would expand and push down content2-4, requiring the user to manually scroll to view the remaining collaps ...

The font implemented in Bootstrap does not appear to be adapting well to different

As I embark on the Bootstrap journey, I find that everything looks great on my desktop browser in terms of responsiveness. However, when I switch to my iPhone 6, it doesn't seem to display as expected... Provided below are a few screenshots: Desktop ...

Exploring the use of dictionaries within Django templates

views.py: return render(request,'images.html',temp) Temp Data: {'cluster1': ['temp/vinoth/cluster1/demo-pic94.jpg', 'temp/vinoth/cluster1/id1.jpg'], 'cluster2': ['temp/vinoth/cluster2/demo-pic94.jp ...

Encountered an error while using JSON.parse(): `SyntaxError: Unexpected token in JSON at position 0`

As I embark on my Node.js development journey, I am faced with a challenge while trying to retrieve data from a JSON file. An error message interrupts my progress: SyntaxError: Unexpected token  in JSON at position 0 at Object.parse (native) Below is ...

What causes req.body to be null after using event.preventDefault() in conjunction with fetch api, express, and node.js?

Is there a way to submit a form without causing the page to reload and still retrieve an object from MongoDB using server side scripts? I've tried preventing the default behavior of the form with an event handler to avoid the page refresh, but this ca ...

The custom validation function in jQuery is not triggering

I am facing an issue with my HTML and JavaScript setup, which looks like this: <html> <head> <title>Validation Test</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="htt ...

Tips on refreshing a div using jQuery while maintaining the functionality of addEventListener

Hi, I am facing an issue with updating the "div" element. The refresh works fine, but after refreshing when I try to click on the updated "div", the addEventListener in my JavaScript code does not seem to work anymore. Can someone please explain why this i ...

Generate a dynamic chart using Angular-chart.js on a canvas that is created on the fly

I am facing an issue with displaying a chart or table in a div based on an XHR response. In the case of a chart, I want to replace the div contents with a canvas element that will be used by chart.js to show a graph. When I directly include the canvas ele ...

Issues with jQuery scroll effect not functioning properly in Firefox due to transformation errors

I've encountered an issue with implementing a scroll effect in Firefox. The code works perfectly fine in Chrome, Safari, and Opera, but for some reason, it's not functioning properly in Firefox. I have carefully reviewed the '-moz-transform& ...

Disabling vertical scrollbar in textarea within Bootstrap modal using CSS, jQuery, and C# in .NET MVC framework

I am passing data to the Bootstrap modal using jQuery from my database. The form values can change from a single row to multiple rows. I do not want a scrollbar, but instead I want the textarea element to automatically adjust its height to fit the content. ...

Prepared SQL Statement in NodeJS for MSSQL using WHERE IN clause

I'm using the sql npm package in my Node.js project. Currently, I have an array of product SKUs like this: var skus = ['product1', 'product2', 'product3']; The SQL query stored in a file looks like this: SELECT * FROM ...

Show the checked options retrieved from controller

I am facing an issue with displaying certain checkbox values from the controller. In order to properly save these values, I believe it would be best to declare them in the controller and then use them in the HTML. However, my current code is not successful ...

Distorted image display on Bootstrap card in Internet Explorer

My layout includes bootstrap v4 cards, but I'm having issues with distorted images in Internet Explorer 11. It seems that IE is not recognizing the height: auto attribute from the img-fluid class. Should I set a custom height for the card images? Inte ...

How to efficiently pass multiple inputs from an HTML form to a controller in AngularJS using a single ng

Currently, I have multiple input text boxes in my HTML and I need to send their values to my controller to add them to an object. The challenge I'm facing is figuring out how to pass more than one value using just one ng-model. In my HTML code, I have ...

Using the Backbone.js library to make secure requests over https

Currently, I am developing a single page application that involves using Backbone.js and Marionette on the front end, combined with Django and Tastypie on the back end. Recently, I successfully implemented an SSL certificate on the web server and configure ...

I am encountering an issue with the useRef function not properly detecting visibility

I'm looking to incorporate a fade-in animation into my React div as I scroll and reach a specific section. Unfortunately, the useEffect function that is supposed to detect the scrolling behavior seems to be malfunctioning and I can't figure out w ...

Error in delete operation due to CORS in Flask API

After successfully developing a rest api in Flask and testing all api endpoints with Postman, I encountered an issue while working on an application in Javascript that consumes the resources of my api. The problem lies in consuming an endpoint that uses t ...

Obtain a numerical output from a selection of numbers

I am facing a simple problem that I can't solve due to my lack of knowledge and have not been able to find any solution online. What I want to achieve is: Create a "value 1" from an array of integers. Generate a random "value 2". Check if the rando ...

The hamburger menu appears to be missing when viewing in Safari, while it functions properly on both Chrome and Firefox browsers

My website has a responsive menu that functions perfectly in Chrome and Firefox, but encounters issues in Safari on mobile devices. The site is built using Elementor WordPress and I believe adding some -webkit- properties could solve the problem, but I&apo ...