Create a Bootstrap4 navigation bar that switches from transparent to a background color when scrolled down, then back to transparent when scrolled back up before reaching the

Seeking to enhance my WordPress website with Bootstrap 4's navbar functionality. I aim to achieve a captivating effect where the top navbar remains transparent, gracefully fades out upon scrolling down, fades back in (with a background color) when scrolling up, and finally transitions to transparency before reaching the top.

While using the jQuery code from an example found here, I am unsure how to implement the 'removing the background color before reaching the top' feature.

The provided example code includes:

    $(function () {
      var lastScrollTop = 0;
      var $navbar = $('.navbar');

      $(window).scroll(function(event){
        var st = $(this).scrollTop();

        if (st > lastScrollTop) { // scroll down

          // jQuery full version
          $navbar.fadeOut()

          // CSS3 animation
          // $navbar.addClass("fade-out");
          // $navbar.removeClass("fade-in");

          // No effect required
          // $navbar.hide();
        } else { // scroll up

          // jQuery full version
          $navbar.fadeIn()

          // CSS3 animation
          // $navbar.addClass("fade-in");
          // $navbar.removeClass("fade-out");

          // No effect required
          // $navbar.show();
        }
        lastScrollTop = st;
      });
    });

I came across a similar example where navbar and div were used to determine scroll height for the transition, but I prefer not to rely on a specific div id.

    //jQuery code for collapsing navbar on scroll
    var header_height  = $('.navbar').height(),
        intro_height    = $('.intro-section').height(),
        offset_val = intro_height + header_height;
    $(window).scroll(function() {
      var scroll_top = $(window).scrollTop();
        if (scroll_top >= offset_val) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
                $(".navbar-fixed-top").removeClass("navbar-transparent");
        } else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
          $(".navbar-fixed-top").addClass("navbar-transparent");
        }
    }); 

Appreciate any insights or assistance on this matter.

Answer №1

The example You've discovered utilizes Bootstrap 3, but it's essential to recognize the key disparities between Bootstrap 3 and Bootstrap 4.

With bootstrap 4, you have the option to incorporate classes such as .sticky-top for a sticky Navbar and .bg-transparent for a transparent look.

Here is a functional demonstration:

(function ($) {

    var navbar = $('.navbar');
    var lastScrollTop = 0;

    $(window).scroll(function () {
        var st = $(this).scrollTop();
        // Scroll down
        if (st > lastScrollTop) {
            navbar.fadeOut();
        } 
        // Scroll up but still lower than 200 (change that to whatever suits your need)
        else if(st < lastScrollTop && st > 200) {
            navbar.fadeIn();
            navbar.removeClass('navbar-light bg-transparent').addClass('navbar-dark bg-custom');
        }
        // Reached top
        else {
            navbar.removeClass('navbar-dark bg-custom').addClass('navbar-light bg-transparent');
        }
        lastScrollTop = st;
    });

})(jQuery);
/* For testing purposes */
body {
    height: 2000px;
}

/* Set your background color */
.bg-custom {
    background-color: #333
}
/* Transition effect */
.navbar {
    -webkit-transition: all .3s ease 0s;
    transition: all .3s ease 0s;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<nav class="navbar navbar-expand-lg sticky-top navbar-light bg-transparent">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
        aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
                <a class="nav-link" href="#">Home
                    <span class="sr-only">(current)</span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true"
                    aria-expanded="false">
                    Dropdown
                </a>
                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <a class="dropdown-item" href="#">Action</a>
                    <a class="dropdown-item" href="#">Another action</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="#">Something else here</a>
                </div>
            </li>
            <li class="nav-item">
                <a class="nav-link disabled" href="#">Disabled</a>
            </li>
        </ul>
    </div>
</nav>

It's worth noting that you should utilize the default WordPress jQuery instead of the slim version linked in the Bootstrap 4 page, as it lacks several functions like fadeIn(), fadeOut().

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

Issue with Dependent Drop Down functionality

I am a beginner explorer diving into the world of PHP & MySQL, and I am currently working on creating a dependent drop-down list. The first drop-down seems to be working fine, but I am facing issues linking the second drop-down with the first one. Can anyo ...

How can I match dates in order to run the following code?

If Purchase Date is after 31/Mar/xxxx it should not calculate elap_yend, rem_days, depre_cur, cur_wdv. Also I have to calculate GST with some options that is if SGST and CGST are chosen, I should not calculate IGST else if IGST selected or marked it shoul ...

Tips for aligning a label next to a customized checkbox in a web form

I'm having trouble aligning a label with my custom-styled checkbox. I found this cool CSS toggle switch as a styled checkbox and implemented it using the following HTML: <label> <input id="test" class="cmn-toggle cmn-toggle-round" type="ch ...

In an array where the first 3 images have been filtered using an if statement, how can I show the image at the 3rd index (4th image) starting from the beginning?

In my personal web development project, I'm using AngularJS for the front-end and .NET Core for the back-end to create a website for a musical instrument retailer. The model I'm working with is called "Guitar" and all the guitar data is stored in ...

Editing the app.js file can cause it to malfunction and stop working

As I work on designing a webpage for a construction company using a template, I face an issue with the js file named app.js. Whenever I make edits to the script, the entire HTML page loses its responsiveness as if the js file was never included in the firs ...

How can I implement a jQuery modal dialog that loads a form page with pre-existing jQuery code for Autocomplete functionality?

I am facing an issue where I have a dynamically generated form on a web page and I want to display it using the jQuery UI modal dialog. Previously, I was suggested a solution that worked when my form did not already contain jQuery UI components like Autoc ...

Display a new view upon clicking a button using AngularJS in a single-page web application

I am completely new to AngularJS and currently working on my first project. I apologize in advance if my question seems very basic. In my project, I have created a page using simple HTML with three buttons. When these buttons are clicked, I want to load v ...

Looking for an alternative to document.querySelectorAll?

My issue involves using querySelectorAll('a') to select all buttons, but I only want to target two specific buttons labeled 'Know More'. How can I achieve this? Below is the code snippet in question: const buttons = document.query ...

Refreshing the Datatable does not work when the page state is set to true

Currently, my data table is equipped with a feature that saves the state of the current page. var tbl = $('#datatable').dataTable({ "bStateSave": true, "fnStateSave": function(oSettings, oData) { localStorage.setItem('datatable&apos ...

Stop all other players except the one that is currently active. Utilize a jQuery audio plugin designed for the <audio> HTML element

I am currently using a plugin that styles the HTML5 <audio> element and provides flash fallback for browsers that do not support the .mp3 file format. However, I have run into an issue where if you start playing one song and then click play on anothe ...

What's preventing my link from opening?

I've written this code for two tabs: <li> <a href="#gallery_place" role="tab" data-toggle="tab"> <i class="fa fa-picture-o"></i> <?php _e("Gallery", ET_DOMAIN); ?> </a> </li> <li> <a href ...

Tips for displaying a slug as an HTML ID in a WordPress website

I am attempting to dynamically assign the id attribute with a slug based on the post title, for example id="the_title" if the title is "the title". This would allow me to apply custom CSS and JavaScript specifically to individual posts. While I can achieve ...

Intermittent issue with Ajax form submission

When submitting a form through AJAX to a PHP page, it will either set a session or not. Here's how the process unfolds: The form is submitted via AJAX to login.php Login.php determines whether or not to set a session loginform.php is reloaded into a ...

Tips for preventing a span from disappearing when a hidden div is displayed during onmouseover

, there is a concern about the disappearing behavior of the span with ID "topnavbar" when the display property changes from none to block on a hidden div using onmouseover event. The query is how to ensure that the span remains visible at all times. Additi ...

Unpredictable Behavior of CSS Transition with JS createElement() Function

I'm using JavaScript to create a div element and I'm adding the CSS property transition: .5s linear top; When the user clicks on the element (onmousedown event), it is supposed to smoothly move to the top of the screen and then be deleted using ...

Dynamically using jQuery, a table with alternating rows contains a select box in the background color

I have a table with rows that include select boxes. I want to apply alternating colors to the rows, but the select boxes aren't changing color. How can I achieve this? HTML <table width="100%" cellpadding="0" cellspacing="0" border="0" class="std ...

Validation of input using JQuery

I am currently working on validating a form, with a specific field that needs to be required. Here is the code for the field in question: <p> <label for="lf">Name: </label> <input class="lf" name="name" type="text"/> < ...

Using selected option from dropdown as a value for a hyperlink

I'm attempting to transfer the chosen value from a dropdown menu to my link. This way, when I click on the specific link, it should trigger the corresponding action based on the ID selected from the dropdown. The alert shows the value, but now I need ...

Is it possible to establish borders in relation to the text?

Take a look at this image that illustrates my goal. What I want to achieve is having lines on both sides of a text element (usually a heading tag) that stretch out a specific distance (in this case, 65px). I'm looking for a solution that adjusts dyn ...

Why does the border-radius property not work on my image elements?

Greetings! I have defined an ID named #img in my stylesheet with the property border-radius: 15px; In my HTML, I assigned this ID to a div. However, the images within that div are not getting rounded corners as expected. When using the img selector, it aff ...