Enhance your navbar on user scroll with Bootstrap 4 by moving or adding elements dynamically

I recently built a Wordpress site using Bootstrap 4.5 for the front-end, marking my first experience with Bootstrap. The site currently features the standard sticky Bootstrap 4 navbar as shown in the code snippet below:

<header>
        <nav class="navbar navbar-dark navbar-expand-md bg-dark box-shadow fixed-top">
            
            <a href="https://www.explorecinema.com" class="navbar-brand">
                <h1 class="text-uppercase site-title"><?php bloginfo( 'name' ); ?></h1>
            </a>

            <p class="navbar-text site-description mb-0">
                <?php 
                    $description = get_bloginfo( 'description', 'display' );
                    echo $description; 
                ?>
            </p>

            <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>

            <div class="navbar-collapse collapse justify-content-end" id="navbarCollapse" style="">
              <ul class="navbar-nav">
              
                <li class="nav-item">
                    <a href="https://www.explorecinema.com/about-us/" class="nav-link navbar-right"> About</a>
                </li>
              </ul>
              <form class="form-inline mt-2 mt-md-0">
                <ul class="navbar-nav">
                  <li class="nav-item">
                    <a href="https://www.explorecinema.com/suggest-content/" class="navbar-link btn btn-outline-success">Suggest Content</a>
                  </li>
                </ul>  
              </form>       
            </div>
        </nav>
    </header>
    

The default setup has the page title and filters positioned in the main container below the navbar. However, I want to achieve a styling similar to the mock-up image below when the user scrolls down:

Link to mock-up image: https://i.sstatic.net/RRsFz.png

I'm not familiar with how to implement this feature but I assume JQuery/Javascript might be required. My initial idea is to hide the default header and filters and then add them to the navbar as hidden elements which will become visible upon scrolling. But how can I ensure that the responsive design of the navbar remains intact?

Answer №1

The navigation elements can be initially hidden on the navbar and revealed upon user scroll; a scroll event listener is required for this functionality.

$(document).ready(function() {
  var scrollingNow = (e) => {
    if (window.scrollY > 50) {
      if ($('#toggleOnScroll').hasClass('hideHeading')) {
        $('#toggleOnScroll').removeClass('hideHeading')
        $('#toggleOnScroll').addClass('showHeading')
      }
    } else {
      if ($('#toggleOnScroll').hasClass('showHeading')) {
        $('#toggleOnScroll').removeClass('showHeading')
        $('#toggleOnScroll').addClass('hideHeading')
      }
    }
  }
  console.log('$ works');
  window.addEventListener('scroll', scrollingNow);
});
.hideHeading {
  display: none
}

.showHeading {
  display: block;
  color: #fff
}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"gt;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<header>
  <nav class="navbar navbar-dark navbar-expand-md bg-dark box-shadow fixed-top">
    <h2 id='toggleOnScroll' class='hideHeading'>Show Me on Scroll</h2>

    <a href="https://www.explorecinema.com" class="navbar-brand">
      <h1 class="text-uppercase site-title">
        <?php bloginfo( 'name' ); ?>
      </h1>
    </a>

    <p class="navbar-text site-description mb-0">
      <?php 
                $description = get_bloginfo( 'description', 'display' );
                echo $description; 
            ?>
    </p>

    <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>

    <div class="navbar-collapse collapse justify-content-end" id="navbarCollapse" style="">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a href="https://www.explorecinema.com/about-us/" class="nav-link navbar-right"> About</a>
        </li>
      </ul>
      <form class="form-inline mt-2 mt-md-0">
        <ul class="navbar-nav">
          <li class="nav-item">
            <a href="https://www.explorecinema.com/suggest-content/" class="navbar-link btn btn-outline-success">Suggest Content</a>
          </li>
        </ul>
      </form>
    </div>
  </nav>
</header>

this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some
text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/> this is some text <br/><br/><br/>this
is some text <br/><br/><br/> this is some text <br/><br/><br/>

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

Looks like an error has occurred: "Swal has not been defined"

I'm currently working on a small project that involves using CodeIgniter, VueJs, and the Sweet Alert Javascript library. However, I encountered an error in my console stating ReferenceError: "Swal is not defined" when I try to call swall.fire({}) with ...

Starting a Node server by running a JavaScript file on server startup

I have a piece of Node.js code (scheduler and a few database queries) that I need to run every time the Express app is started on the node server. One possible solution I thought of is creating a batch file with two lines: one to start the node server an ...

Chrome's refusal to cooperate with CSS animation troubleshooting

This is a duplicate warning, my apologies for that. After reading several similar posts and attempting various solutions, I am still unable to get it to work. I have a very basic animation that involves hiding, showing, and image. #top_heading .chmurka2 ...

Prevent a HTML button from being clicked multiple times before it disappears (using Django)

I am currently working on a Django project that involves events where users can join by adding their user_id and event_id to the attend model. On the event page, there is a join button form that, when clicked, adds the user to the attendees list. After cli ...

Is it possible to attach a PDF file using just the PDF URL?

My current project involves an ionic application that performs calculations based on user inputs. Once the calculations are complete, the results are converted into a PDF using the generatePDF API call. Additionally, there is a requirement to email the gen ...

What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth. My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoin ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

The Stormpath-express login feature is incompatible with basic username and password authentication, experiencing issues

My goal is to develop a NodeJS API system tailored for an electron-based desktop application. The main feature of this app should be basic login functionality using username and password, with subsequent API calls requiring authentication via IDs and secre ...

My attempts to load the .mtl and .obj files using THREE.js have been unsuccessful

I've been working on creating a 3D model viewer using three.js, but I'm encountering issues with loading .mtl and .obj files. Despite following a tutorial at , the only model that loads successfully is the female one. Here is the code snippet I ...

What could be causing Firestore to round numbers with more than 16 digits?

I am encountering an issue while attempting to save a 20-digit number from my Vue app into my Firestore database. The problem arises when it appears that the last 3 digits are being rounded off, and any numbers starting with a zero are having the zero r ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

What could be the reason behind the failure of JSON.stringify() on this particular array?

I am encountering an issue with an array that I have declared like this: array = []; The array contains values that look like this - .... ChIJOaegwbTHwoARg7zN_9nq5Uc:"ChIJOaegwbTHwoARg7zN_9nq5Uc" ChIJXTwCdefHwoAR9Jr4-le12q4:"ChIJXTwCdefHwoAR9Jr4-le12q4 ...

Create a new function within the GraphQL Resolvers file

I am trying to define a function within the same ts file as where I specify the resolvers export const resolvers = { Query: { books: () => { return [ { title: 'Harry Potter and the Chambe ...

I am experiencing the issue of unexpected borders showing up on the HTML/CSS page that I designed

Greetings, amazing community at StackOverflow! I recently completed an HTML/CSS Project as part of a Codecademy Intensive course. If you're curious to see the project in action, feel free to check it out on GitHub by visiting this link. One thing I ...

Firebase enables email verification and user login for secure access to the page

I have developed a form "main.html#!/register" where users can input their first name, last name, email, and login details. Once these details are entered, an email verification is sent before they can proceed to the page "main.html#!/success". The positi ...

"Challenges Encountered When Using Vue.js to Handle Image Paths Containing Variables

I've come across a challenge while trying to create a dynamic image path based on the props passed in Vue.js. Despite my efforts, such as using variables for the images, CSS variables, and moving the images to the src folder (although this caused issu ...

Unable to load variables into site.css in order for Flask app to successfully render home.html

I'm encountering difficulties in getting my site.css file to accept two variables passed in from my app.py using Jinja2 templates, namely {{ variable }}. In app.py, I have defined two variables named empty_fill_line and fill_line, which dynamically up ...

Building a multi-panel electron app with React and Angular

Is it possible to create a multi-window Electron application with React/Angular, where each window is powered by its own HTML file? In traditional React/Angular applications, the build process typically results in a single HTML file (e.g., index.html). Ho ...

Is Optional Chaining supported by Next.js on Vercel?

While Next.js does support Optional Chaining, I have encountered an issue when trying to deploy the following code snippet: module.exports = { experimental: { outputStandalone: true, }, images: { domains: process.env.NEXT_PUBLIC_IMAGE_DOMAINS ...

Substitute an item with another -JavaScript

While I understand this is a rather common question, my search through various sources has yielded answers that involve libraries, ES6, or methods not supported by native JavaScript. My goal is to simply replace one object with another based on a condition ...