Employing JavaScript to display or conceal a <div> element while scrolling

I'm looking to create a customized sticky navigation bar through Javascript, but I have never written my own code in this language before.

My approach involves implementing two sticky navigation bars that appear and disappear based on scrolling behavior. Here's how I envision it:

  • Initially, the first navigation bar (yellow) will be visible with a position 100px from the top, set as top:100px.
  • Upon scrolling, I want the yellow <div> to vanish using display:none.
  • Simultaneously, as the yellow navigation bar disappears, I intend for the orange navigation bar to appear with top:200px.
  • Currently, the orange bar is displayed at the start when it shouldn't... only one bar should be shown at any given moment. I expect the bars, both <div> elements, to continue appearing and disappearing even with multiple scrolls up and down.

There seems to be an issue with my javascript code and Codepen is indicating that $ is undefined.

https://codepen.io/G1111/pen/RwBPrPR

$(window).scroll(function() {
  Testvariable = $(window).scrollTop();

  if (Testvariable == 0) {
    document.getElementById("stickys").style.display = "normal";
    document.getElementById("stickys2").style.display = "none";
  } else {
    document.getElementById("stickys").style.display = "none";
    document.getElementById("stickys2").style.display = "normal";
  }
});
#stickys {
  top: 100px!important;
  background-color: yellow;
  height: 100px;
  position: fixed;
  position: fixed!important;
  box-sizing: border-box;
  margin: 0 0% 0 0%!important;
  padding: 0!important;
  width: calc(60vw - 0%);
  left: calc(20vw - 0%);
  right: calc(20vw - 0%);
  width: calc(100vw - 0%);
  left: 0px;
  right: 0px;
  opacity: 1;
}

#stickys2 {
  top: 200px!important;
  background-color: orange;
  height: 100px;
  position: fixed;
  position: fixed!important;
  box-sizing: border-box;
  margin: 0 0% 0 0%!important;
  padding: 0!important;
  width: calc(60vw - 0%);
  left: calc(20vw - 0%);
  right: calc(20vw - 0%);
  width: calc(100vw - 0%);
  left: 0px;
  right: 0px;
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stickys">
  My first sticky navigation bar. Show initially, then hide when slighest scroll, that is when Testvariable>0. Here, top:100px
</div>
<div id="stickys2">
  My second sticky navigation bar. Hide initially, then show when slighest scroll, that is when Testvariable>0. Here, top: 200px.
</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>

Answer №1

To start, swap out display = "normal"; with display = "block";.

Next, make sure to include a call to $(window).scroll(); after attaching the scroll event handler for displaying or hiding your navigation bars based on the window scroll position :

$(window).scroll(function() {
  Testvariable = $(window).scrollTop();
  if (Testvariable == 0) {
    document.getElementById("stickys").style.display = "block";
    document.getElementById("stickys2").style.display = "none";
  } else {
    document.getElementById("stickys").style.display = "none";
    document.getElementById("stickys2").style.display = "block";
  }
});

$(window).scroll();
#stickys {
  top: 100px!important;
  background-color: yellow;
  height: 100px;
  position: fixed;
  position: fixed!important;
  box-sizing: border-box;
  margin: 0 0% 0 0%!important;
  padding: 0!important;
  width: calc(60vw - 0%);
  left: calc(20vw - 0%);
  right: calc(20vw - 0%);
  width: calc(100vw - 0%);
  left: 0px;
  right: 0px;
  opacity: 1;
}

#stickys2 {
  top: 200px!important;
  background-color: orange;
  height: 100px;
  position: fixed;
  position: fixed!important;
  box-sizing: border-box;
  margin: 0 0% 0 0%!important;
  padding: 0!important;
  width: calc(60vw ‐ 0%);
  left: calc(20vw ‐ 0%);
  right: calc(20vw ‐ 0%);
  width: calc(100vw ‐ 0%);
  left: 0px;
  right: 0px;
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stickys">
  The initial sticky navigation bar that will be visible at first but disappear upon scrolling even slightly, triggered when Testvariable>0. This one is positioned at top:100px.
</div>
<div id="stickys2">
  The secondary sticky navigation bar that remains hidden initially and appears upon slight scrolling, also responsive to Testvariable>0. Here it's set to position at top:200px.
</div>
.<br>... [additional content truncated for brevity]

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

Having trouble getting the webpage to update after entering information?

My current project involves automating a website using selenium python. I've encountered an issue where manually entering J590 into the target textbox requires clicking or pressing tab to refresh the page, resulting in an available option in a dropdow ...

Transferring data from one of the three submitted forms by utilizing jQuery's AJAX function

Currently, I am facing a challenge with three forms on a website, where two of them are located in modal windows. My goal is to use ajax to send input values such as name, phone, email, and radio button selections (which vary in each form). However, I have ...

Mastering the art of gracefully transitioning to a fallback option when CSS grid

When it comes to creating a simple grid of squares (3x3 at most, filling in top to bottom left to right), I have encountered challenges with both flexbox and grid. The DOM structure required for each method seems incompatible or too complex to support both ...

The MySQL database will need to contain an HTML form with specific styling attributes

I have been experimenting with creating an HTML form that allows users to add style attributes to their posts, such as Bold, Center, Font-Size, Link, Image, and more. However, my English skills are not the best, so I apologize if I am not explaining my que ...

Error message: Unable to iterate through a non-iterable object in React reducer

I find myself in a unique predicament and could use some assistance. userData : { isValidCheckup: true, accounts: { userAccount: [ { accountType: 'checkings', includeInCheckup: false }, { accountType: 'check ...

What is the process for uploading an image and entering text into the same row in Google Sheets?

Hello, I am currently working on a Google Script web app that enables users to upload 10 photos along with comments for each photo. This information will then be inserted into a Google Sheet when the user clicks the 'upload' button on the web app ...

What are the best strategies for creating HTML website designs that are both scalable, adaptable, and versatile?

As a beginner in HTML website design, I have recently started using HTML, CSS, jQuery, and JavaScript for designing websites. After creating a site with almost forty webpages, the client requirements are changing, requiring changes to be made across all ...

(no longer supported) We are unsure about the usage of /deep/, >>>, and ::ng-deep, ::v-deep

Since /deep/ has been deprecated, I have found that using global styles instead is the only viable solution. Does anyone know of an alternative solution where we can still maintain encapsulation or scoped styling? ...

Generating a JSON Object by combining elements from multiple arrays

I need assistance in creating a single Json object from two arrays using JavaScript or jQuery. The data is stored in the database in the format shown below: clob_field_1: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 etc etc ... clob_field_2: 8106.23, 7856.49, 8009.15, ...

Implementing the if/shim binding in Knockout.js

In my project, I am looking to develop a unique custom binding that functions similarly to the if binding. However, instead of completely removing the element from view, I want it to be replaced with another element of equal height whenever it needs to be ...

Issues with Jquery Div sliding transitions from right to left are not functioning correctly

Creating page transitions in jQuery similar to "http://support.microsoft.com/." Encountering an issue where after the page transitions are completed, they start from the left instead of the expected right direction. Referencing this fiddle (Working Code) ...

Sharing the input value with a service in Angular 4

I am a beginner when it comes to Angular 4. I currently have a variable named "md_id" which is connected to the view in the following way. HTML: <tr *ngFor="let item of driverData"> <td class="align-ri ...

Receiving a "Undefined index" error while passing information to a PHP script via jQuery

I have extensively researched this issue, including reading numerous StackOverflow questions, but I am still unable to find a solution. My problem involves retrieving the 'id' attribute value of an HTML 'a' element with jQuery when the ...

Perform an AJAX call from the main file after inserting data using AJAX beforehand

I am in need of assistance with a question I have. On a page, an AJAX function is executed after the page finishes loading, creating a table in PHP that contains two buttons: one for changing passwords and the other for deleting. This table is then injecte ...

Add a luminous shine to a THREE.TextGeometry element within the Three.js environment

After conducting extensive research on Google, I am still trying to determine if it is possible to achieve a glow effect within the three.js environment. My goal is to create a glowing effect based on TextGeometry rather than a simple primitive shape like ...

Implementing advanced checkbox filtering feature in React

Does anyone have experience with creating dynamic Checkbox filtering in React using Material-UI? I'm finding it challenging because the checkbox options are generated dynamically from incoming data and need to be categorized by type of Select componen ...

Ways to specify distinct css styles according to varying number of elements

I need the Button element to always take up 100% of the container, no matter how many elements are inside. Check out my Fiddle link here: Js Fiddle Link <div class="inputFieldBoolean buttonSeries" data-type="Boolean"><button class="true" data-va ...

Leverage Vue3's v-html feature without the need for additional wrapping tags by using script

Is it possible to use Vue's v-html directive within a Vue 3 <script setup> setup without needing an additional wrapping tag? I am looking to achieve something similar to the following: <script setup> const html = ref(`<pre></pre& ...

The nodes on a 2-dimensional grid overlap each other when the browser window is resized

In my project, I have set up a grid with 24 rows and 64 columns, totaling to 24x64 nodes. However, I am facing an issue where the nodes overlap when I open the console window. I am looking for a solution to automatically resize all nodes based on changes ...

Seamless Integration of jQuery Functions

I am in need of some assistance with passing a chain of jQuery methods into a function as an argument. The goal is to have dynamic methods executed on a DOM object. This functionality would be particularly useful for writing qUnit tests where centralizat ...