Positioning a div above a Bootstrap navbar that disappears when scrolling

I am currently using bootstrap to design a website, and I am attempting to create a div that would initially appear above the navbar on an unscrolled webpage. However, once the user starts scrolling, I want this div to disappear and have the navbar fill its position.

While my current setup kind of works, I believe there must be a more efficient way to achieve this effect. Here is the code snippet I am using:

HTML

<div class="container">
    <div class="row">
        <div class="hidden-xs col-md-offset-8 col-sm-offset-8" style="padding:2px 0 3px 0;">
            <span class="btcall">Call for a free quote call - <span class="badge"><i class="glyphicon glyphicon-earphone"></i> 1300 123 456</span>
        </div>
    </div>
</div>
<nav class="navbar navbar-default navbar-fixed-top topnav" role="navigation">
etc etc

JavaScript

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('nav').addClass('shrink');
  } else {
    $('nav').removeClass('shrink');
  }
});

CSS

.navbar-fixed-top {
     top:25px;
 }

nav a {
  padding-top: 20px !important;
  padding-bottom: 20px !important;
  font-size: 16px;
}

nav .navbar-toggle {
  margin: 13px 15px 13px 0;
}

.navbar-brand {
  font-size: 30px !important;
  margin-top:-15px;
}

.navbar-fixed-top.shrink {
    top:0px;
}

 nav.navbar.shrink {
  min-height: 35px;
}

nav.shrink a {
  padding-top: 15px !important;
  padding-bottom: 10px !important;
  font-size: 14px;
}

nav.shrink .navbar-brand {
  font-size: 20px !important;
  margin-top:0;
}

Although it somewhat does the job, I know there must be a better way to accomplish this. Ideally, I would like the element to be fixed to the navigation bar and hidden upon scrolling, rather than being locked in place and only revealed when the browser is scrolled all the way up to the top.

Answer №1

When your navigation bar is fixed to the top of the window and scrolls with the page, you may want a div to appear above that bar only when the user reaches the top of the page. The following code can help achieve this.

If this solution doesn't fit your requirements, please provide more details about the UI or consider creating a jsfiddle.

$(window).scroll(function() {
  if ($(document).scrollTop() > 50) {
    $('.hideMe').fadeOut('slow');
  } else {
    $('.hideMe').fadeIn('slow');
  }
});
.floatMenu {
    position:fixed;
    top:0;
    left:0;
    width:100%;
}

/* The CSS below is specifically for a made-up example navigation */

li {
    display: inline;
}
.pre-container{
  background-color:#cccccc;
}

.hideMe{
  background-color:#999999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pre-container floatMenu">
<div class="container hideMe">
  <div class="row">
    <div class="hidden-xs col-md-offset-8 col-sm-offset-8" style="padding:2px 0 3px 0;"> 
      <span class="btcall">Call for a free quote call - </span>
      <span class="badge"><i class="glyphicon glyphicon-earphone"></i> 1300 123 456</span> 
    </div>
  </div>
</div>
<nav  class="navbar navbar-default navbar-fixed-top topnav" role="navigation">
  <!-- This is just an example menu -->
  <ul>
  <li><a href="default.asp">Home</a></li>
  <li><a href="news.asp">News</a></li>
  <li><a href="contact.asp">Contact</a></li>
  <li><a href="about.asp">About</a></li>
</ul>
  </nav>
</div>
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><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

Send data from input to controller without using $scope

I am encountering an issue with the code below. Typically, I would resolve this problem using $scope, but this time I have been asked to find a solution without utilizing $scope in the controller. I am implementing the "controller as" syntax for managing ...

Tips for eliminating double quotes from an input string

I am currently developing an input for a website that will generate a div tag along with its necessary child elements to ensure the website functions correctly. I have a couple of key questions regarding this setup: <!DOCTYPE html> <html> < ...

Show a variety of pictures in a random arrangement?

Looking for some help here! I'm trying to shuffle my images in a random order each time the page is refreshed. It's like a game of musical chairs but with pictures! Does anyone know how to achieve this? I've done some searching, but haven& ...

It appears that the margin is malfunctioning

Let's cut to the chase - I want to add a chat sidebar to my website, but I'm having trouble adding margins to make it close in properly. Here's the code snippet: HTML <div class="inner-chat"> <div class="chat-box-messages"> ...

Using jQuery and $.ajax to update <td> contents

I need assistance with updating the content of a table using jQuery. Here is an example of my table structure: <table id="table-name"> <tr><td id="td-name">something</td></tr> <tr><td id="td-name">somethin ...

Testing the API call triggered by the submit button

In my LoginForm template, I have passed the onFinish function to the prop onFinish using Antd Form. Here is the implementation of my onFinish function: This function invokes the api method from class methods Services and AuthService. const onFinish = asyn ...

Retrieve the selected option from the dropdown menu in the specified form

What should I do if I have numerous products and want users to be able to add new dropdown boxes dynamically? When the submit button is clicked, only the value of "category[]" within the form should be retrieved. https://i.stack.imgur.com/v1fnd.png Below ...

Executing jQuery post request on a div loaded via ajax

I'm facing a challenge with my webpage. I have a section where the content of a div is loaded via ajax. This div contains forms, and after submission, it should update to display the new content without refreshing the entire page. Can anyone guide me ...

Struggling with PHP variables and AJAX JavaScript

Hey everyone, I've made some edits and have a new question regarding a similar issue. On test.php in my Apache server, I have a PHP script that connects to a database and retrieves data from a table. <?php $con = mysqli_connect("localhost", "user" ...

Unresolved Issue: Jquery Modal Fails to Activate on Subsequent Click for Ajax-

When I make an Ajax call, I load HTML into a div. This HTML content contains a jQuery modal that opens when clicked. However, on the first click, the modal opens correctly. On subsequent clicks, I receive the following error in the console: Uncaught Type ...

Pressing the button will activate the Ctrl+z and Ctrl+y key commands

I have created two separate buttons for triggering actions equivalent to pressing Ctrl+z and Ctrl+y. I am attempting to make these actions occur with the click of a single button. However, when trying to set up the functionality to trigger Ctrl+z and Ctr ...

While working on a project in React, I successfully implemented an async function to fetch data from an API. However, upon returning the data, I encountered an issue where it was displaying as a

I am working with React and TypeScript and have the following code snippet: const fetchData = async () => { const res: any = await fetch("https://api.spotify.com/v1/search?q=thoughtsofadyingatheist&type=track&limit=30", { met ...

Do you think there is a more efficient way to solve this issue?

const [active, setActive] = React.useState(["active", "", "", "", ""]);``your unique text`` const hrefs = React.useMemo( () => ["/", "/about", "/skills", "/projects", "/contact"], [] ); React.useEffect(() => { setInterval(() => { ...

Toggling the visibility of a div using JavaScript

When I click the button, I want to show and then hide a div. However, it doesn't work on the first click - only on the second click. How can I make it work on the first click? HTML <p>Click the button</p> <button onclick="myFu ...

Discover the position of a dynamically added element

Is there a way to identify the specific dynamically added checkbox that was clicked, whether by index or name? I came across a similar question with a solution in this JSFiddle: JSFiddle Instead of just displaying "clicked", I would like it to show someth ...

Vue js parent-child communication using event bus fails to function

Is there any way to successfully communicate between non parent child components in vue js document? I followed the instructions in the vue document, but unfortunately, my code did not work as expected. Below is a snippet of my code: The structure of the ...

What is the best way to tally the frequency of words in a collection of URLs using JavaScript?

I have a JSON object in WordPress that contains a list of URLs. I would like to determine the frequency of occurrence of the second part of each URL. Currently, the code snippet below is able to extract the remaining part of the URL after the prefix https ...

Error in Vue.js: Trying to access properties of an undefined object

My understanding of vue.js is limited, but based on what I know, this code should work. However, when attempting to access the variable in the data property, it seems unable to locate it. data: function() { return { id: 0, clients: [] ...

Leveraging data from various Fetch API calls to access a range of

As a beginner with Fetch API and Promises, I have encountered an issue that I hope someone can help me with. My code involves fetching event data with a token, extracting team ids, and using these ids to fetch more information from another endpoint. Every ...

Tips for transferring data from a parent component to a child component in React?

Recently, I've been restructuring a small application that was initially confined to one file by breaking it into its own separate components. Right now, I have a child component called UsersTable which I am displaying within the parent component User ...