conceal the bootstrap navigation bar while the page is being

Struggling to toggle a Bootstrap navbar on scroll? Need some guidance from the pros out there. I admit, my Bootstrap and jQuery skills are pretty basic. The browser console doesn't throw any errors, and I've experimented with fadeIn, fadeOut, addClass, and removeClass without success.

$(document).ready(function() {

  var banner = $("#navscroll");
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= banner.height()) {
      $("#banner").hide();

    } else {
      $("banner").show();
    }
  });

});

console.log();
body {
  background-color: azure;
}

.divi {
  width: 500px;
  height: 500px;
}

#divi1 {
  background-color: red;
}

#divi2 {
  background-color: greenyellow;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
  <!-- Stylesheet for Mysite -->


  <title>My Site</title>

</head>

<body>

  <!-- Banner -->
  <div id="banner" class="container-fluid">
    <nav id="navscroll" class="navbar navbar-toggleable-sm navbar-light fixed-top">
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
      <a class="navbar-brand" href="#">My Site</a>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav">
          <a class="nav-item nav-link active" href="#">Me<span class="sr-only">(current)</span></a>
          <a class="nav-item nav-link" href="#">What I do</a>
          <a class="nav-item nav-link" href="#">Find Me</a>
        </div>
      </div>
    </nav>
  </div>
  <!-- Banner -->

  <!-- Divs -->
  <div class="container-fluid">
    <div id="divi1" class="divi"></div>
    <div id="divi2" class="divi"></div>
  </div>
  <!-- Divs -->



  <!-- jQuery first, then Tether, then Bootstrap JS. -->

  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>

</html>

Answer №1

There are a couple of issues that need to be addressed for your code to properly display the navbar when scrolling up:

  1. The line $("banner").show(); should have "#" before banner.
  2. When hiding an element, its height is not preserved. This causes unexpected behavior when checking the navbar height after it has been hidden. To resolve this, it is recommended to save the height beforehand and compare it with the saved variable.

Here is the corrected code:

$(document).ready(function() {
  var banner_height = $("#navscroll").height();
  var lastScrollTop = 0;
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    var currScrollTop = $(this).scrollTop();
    if (scroll >= banner_height && currScrollTop > lastScrollTop) {
      $("#banner").hide();
    } else {
      $("#banner").show();
    }
    lastScrollTop = currScrollTop;

  });

});
body {
  background-color: azure;
}

.divi {
  width: 500px;
  height: 500px;
}

#divi1 {
  background-color: red;
}

#divi2 {
  background-color: greenyellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Necessary meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
  <!-- Stylesheet for Mysite -->

  <title>My Site</title>

</head>

<body>

  <!-- Banner -->
  <div id="banner" class="container-fluid">
    <nav id="navscroll" class="navbar navbar-toggleable-sm navbar-light fixed-top">
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
      <a class="navbar-brand" href="#">My Site</a>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav">
          <a class="nav-item nav-link active" href="#">Me<span class="sr-only">(current)</span></a>
          <a class="nav-item nav-link" href="#">What I do</a>
          <a class="nav-item nav-link" href="#">Find Me</a>
        </div>
      </div>
    </nav>
  </div>
  <!-- Banner -->

  <!-- Divs -->
  <div class="container-fluid">
    <div id="divi1" class="divi"></div>
    <div id="divi2" class="divi"></div>
  </div>
  <!-- Divs -->

  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>

</html>

Answer №2

Don't forget to set the banner height variable outside of the scroll function and also make sure to include the # symbol in your script. Your code should look something like this:

$(document).ready(function(){

                var banner = $("#navscroll");
                var bannerHeight = banner.height();
                $(window).scroll(function(){
                    var scroll = $(window).scrollTop();
                    if (scroll >= bannerHeight){
                        $("#banner").hide();
                    } else {
                        $("#banner").show();
                    }
                });

        });

Answer №3

I went ahead and made some adjustments to the code for you while also adding in some helpful comments. Feel free to open up the console and scroll to see the changes taking place.

The issue stemmed from comparing the scroll height to the banner height, which was experiencing a change from 40 to -16 when hidden. To remedy this, I made sure to save the banner's initial height beforehand.

        
$(document).ready(function(){
    var banner = $("#navscroll");
    var bannerStartHeight = $("#navscroll").height();
    
    $(window).scroll(function(){
        var scroll = $(window).scrollTop();
        
        console.log("SCROLL: "+scroll)
        console.log("BANNER HEIGHT:"+banner.height())
        console.log("BANNER START HEIGHT: "+bannerStartHeight)
        
        if (scroll >= bannerStartHeight){
            $("#banner").hide();
        } else {
            $("#banner").show(); // don't forget the #
        }
    });
});

I hope these changes are helpful to you!

Answer №4

It is recommended to calculate the banner height outside of the scroll function.

$(document).ready(function() {

  var banner = $("#navscroll");
  var bannerHgt = banner.height();
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll >= bannerHgt) {
      $("#banner").hide();
    } else {
      $("#banner").show();
    }
  });

});

console.log();
 body{
    
            background-color: azure;
        }

        .divi{

            width: 500px;
            height: 500px;
        }

        #divi1{

            background-color: red;
        }

        #divi2{

            background-color: greenyellow;
        }  
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"></aDoIDEWoOUDeILUWEODEWlOSDeSfLoWeEdesrrnTheyMlsdfvOWhoWS&DhttpmrnytzMLsOIffOEWhsuitmflash-fssSEWsletysOntsstESfPLEMNssiOEDE

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

Triggering a click event on an anchor <a> element

Seeking help with a Javascript event query. I have an <a> tag set up like this: <a id='aTag' href='http://example.com'>Click to redirect</a> When attempting to trigger the click event using: <script> $('#a ...

What is the best way to reveal or conceal a div element on mouseover with jQuery?

Currently, I have a table with the following structure. <table> <tr> <td id="divOne">div one</td> <td id="divOne">2222</td> </tr> <tr> <td id="divOne">d ...

Scaling a mesh and BufferGeometry vertices using THREE.OBJLoader

Utilizing the THREE.OBJLoader, I successfully loaded a 3D model into my scene. Subsequently, I have the necessity to scale it by 10 and then extract its vertices position. I am aware that the THREE.OBJLoader provides a BufferGeometry, allowing me to acce ...

Modify the JavaScript window.navigator

I am attempting to modify window.navigator, but am facing difficulties in doing so: -- [10:40:28.802] window.navigator['buildID']; [10:40:28.811] "20121129162756" -- [10:40:47.225] window.navigator['appCodeName'] = "I want to change it ...

Issue with Opacity in IE8

The layer opacity works well in Firefox and Chrome, but struggles in IE8. $('document').ready(function () { $('.out-of-stock').each(function () { $('.productImage', $(this)).css('opacity', '.25'); ...

Issue with Bootstrap side navbar not collapsing when clicked on a link

Currently, I'm working on creating a website for a friend. While I used to have some experience with coding in the past, it has been a while and I am a bit rusty. This time around, I decided to use bootstrap for the project. However, I'm struggli ...

Moving from one page to another

I am attempting to create a transition effect between sections within a single-page application. All the sections are contained on the same page, with only one section displayed at a time while the rest are set to display none. When a specific event is tri ...

Example of AngularJS UI-Router Login Feature

Currently, I am delving into the realms of angularjs and bootstrap to develop a web application that will consist of two distinct sets of views - public and private. In the public view, all users will have access to it and there will be a specific top men ...

Ensure that the view remains consistent while navigating a table that contains expanding concealed information

My table is dynamically populated with data within a div that has overflow: scroll and height set properties. The issue I face is that the data populates from the top, making it difficult to keep track of specific rows when scrolling within the #container ...

Moving a Node project to a different computer

I am looking to transfer my Angular project from a Windows machine to a Mac. I attempted to copy the folder and run npm install, but encountered an issue. Here is the error message I received: sh: /Users/pawelmeller/Documents/hotel/angular4/node_modules/ ...

Using an HTML img tag without success, despite having the correct link

My HTML img tags are not working even though the link is correct. I have been attempting to resolve this issue for quite some time by researching multiple websites and trying various solutions, but unfortunately, nothing seems to be working. All I want i ...

"Discovering the missing numbers in an array using JavaScript - a step-by-step guide

I have a series of numbers in a string, such as "3 -1 0 5". My goal is to create another string that lists the missing numbers from the original sequence once it has been sorted. For example, if the original array is sorted as [-1, 0, 3, 5], then ...

Tips for changing the color of MUI TextField in React.JS?

Is there a way to customize the color of the TextField frame? It always shows up as black, making it hard to use in dark mode. I am looking to change the color of both the label and the input line. return ( <div align="center" ...

Leveraging a JQuery plugin to generate dynamic HTML content

Recently, I came across a fantastic JQuery plugin that Stack Overflow graciously provided for everyone to use :) Auto-size dynamic text to fill fixed size container However, I encountered a little challenge while trying to implement this on an HTML eleme ...

"Vue is throwing an error because it cannot set the property '$offlineStorage' on an undefined object. How can this issue be resolved

While working on my vue ionic app, I integrated the plugin available at https://github.com/filrak/vue-offline. However, upon installing the plugin, an error was encountered: vue-offline.js?bf4e:193 Uncaught TypeError: Cannot set property '$offlineStor ...

Is there a way to extract the content from a dynamic textbox using a dynamic button in HTML and AJAX?

My current task involves fetching data from a database and updating the records individually. I have created a table with a text input field and a button that will be generated dynamically for each record. The text input field is populated with the previou ...

What is the best way to eliminate a notice in PHP related to a checkbox?

I'm encountering an issue when submitting a form without selecting the checkbox. In this case, a NOTICE is displayed. Can someone please advise on how to prevent this from happening? I find it interesting that when using a text input instead of a chec ...

Focus on targeting dynamic IDs such as #event_rules_attributes_0_interval, #event_rules_attributes_1_interval, etc. using CSS3 styling

Styling input tags using their IDs can be very convenient due to the higher precedence weight they hold compared to classes. For instance, I set a default width for input.text elements within a specific container: .details .metadata input.text { width: 2 ...

I must duplicate a pattern to accommodate various object dimensions

Let me clarify something. I am faced with the challenge of handling multiple textures, and I already know which method to employ for this task. The solution I identified was to use UV mapping on geometries to repeat textures. However, the issue I'm ...

Sleek transitions for navigating between cells in a data table

I am looking to implement a smooth animation for cell navigation. Check out what I currently have: http://jsfiddle.net/0ardb3u0/ When the mouse hovers over a cell, I want the full column and row of that cell to be selected and highlighted in blue. How ...