Determine the exact scroll position needed to reveal the element when scrolling in reverse

I'm looking for a way to make my div disappear when I scroll down and reappear immediately when I start scrolling back up. Currently, it only works when I reach a certain position instead of taking effect right away. I need assistance in calculating the scroll position so that the effect happens instantly. Here is the code I have been working on:

window.addEventListener('scroll', function() {
  if (window.scrollY < 5) {
    document.getElementById('search-bar-scroll').classList.add('scrolled');
  } else {
    document.getElementById('search-bar-scroll').classList.remove('scrolled');
  }
});
* {
  margin: 0;
  padding: 0;
}

img,
fieldset {
  border: none;
}

body *,
*:after,
*:before {
  box-sizing: border-box;
}

html,
body {
  height: 250vh;
}

.main-wrapper {
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.search-bar-scroll {
  background: #1e5da5;
  position: fixed;
  height: auto;
  width: 100%;
  left: 0;
  top: 0;
  opacity: 0;
  transition: 0.3s ease;
}

.scrolled {
  opacity: 1;
  transition: 150ms all;
}
<div class="search-bar-scroll" id="search-bar-scroll">
  <fieldset class="home-header-search">
    <div action="#" id="scroll-input-container">
      <p>Hello World</p>
    </div>
  </fieldset>
</div>

Answer №1

UPDATE.

After further consideration, I have a solution for your query. You can track the scroll position by storing the last Y coordinate.

let lastScrollY = 0;
window.addEventListener('scroll', function(e) {
    if (window.scrollY == 0 || window.scrollY<lastScrollY) {
      document.getElementById('search-bar-scroll').classList.add('scrolled');
    } else {
      document.getElementById('search-bar-scroll').classList.remove('scrolled');
    }
    lastScrollY = window.scrollY;
});
* {
    margin: 0;
    padding: 0;
  }

  img,
  fieldset {
    border: none;
  }

  body *,
  *:after,
  *:before {
    box-sizing: border-box;
  }

  html,
  body {
    height: 250vh;
  }

  .main-wrapper {
    max-width: 1400px;
    margin-left: auto;
    margin-right: auto;
  }

  .search-bar-scroll {
    background: #1e5da5;
    position: fixed;
    height: auto;
    width: 100%;
    left: 0;
    top: 0;
    opacity: 0;
    transition: 0.3s ease;
  }

  .scrolled {
    opacity: 1;
    transition: 150ms all;
  }

  #header {
    background: #1e5da5;
    padding: 1rem;
    position: sticky;
    top: 0;
    left: 0;
    z-index: 2;
  }
<div class="search-bar-scroll-container">
  <div class="search-bar-scroll scrolled" id="search-bar-scroll">
    <fieldset class="home-header-search">
      <div action="#" id="scroll-input-container">
        <p>Hello World</p>
      </div>
    </fieldset>
  </div>
</div>

Answer №2

Big thanks to Brandon for assisting with my solution, which turned out perfectly! This answer is in response to Rango's recommendation to utilize the wheel event, and it worked flawlessly!

Here's my approach:

let scrollPosition = 0;
let scrollElement = document.getElementById("search-bar-scroll");

document.addEventListener("wheel", function(e) {
  if (e.deltaY > 0) {
    scrollElement.style.display = "none";
  } else {
    scrollElement.style.display = "block";
  }
});
* {
  margin: 0;
  padding: 0;
}

img,
fieldset {
  border: none;
}

body *,
*:after,
*:before {
  box-sizing: border-box;
}

html,
body {
  height: 150vh;
}

.main-wrapper {
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.search-bar-scroll {
  background: #1e5da5;
  position: fixed;
  height: auto;
  width: 100%;
  left: 0;
  top: 0;
}
<div class="search-bar-scroll" id="search-bar-scroll">
  <fieldset class="home-header-search">
    <div action="#" id="scroll-input-container">
      <p>Hello World</p>
    </div>
  </fieldset>
</div>

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

Alignment issues with menus

Could someone help me with aligning my register and login buttons to the right? I will provide any necessary information upon request. Please note that this is just a small part of a larger menu with additional CSS styling. PHP/ HTML: <a href="<?ph ...

Verify if there are duplicate values present in a table

I have a Table that contains multiple rows, each row having input fields. I need to check for duplicate values within the table. Below is my code where I am currently checking for empty values, how can I modify it to also detect duplicate values? JavaScr ...

Having trouble activating the Tailwind CSS or Intellisense features

I'm having trouble getting my React app to properly style divs using Tailwind CSS. The intellisense feature doesn't suggest any styling options for me either. import './App.css'; function App() { return ( <div className="t ...

Customizing Eclipse Outline View for Cascading Style Sheets (CSS) Files

Is there a way to modify Eclipse's Outline view for CSS files? Specifically, how can I make the outline display comments and create collapsible ranges for groups of CSS rules? Include comments in the outline Create collapsible ranges for groups of ...

Carousel Alert: Ensure that every child within the list is assigned a distinct "key" property

I'm experiencing an issue that is proving to be more challenging than usual, as it appears to be related to a specific library. I understand that using a key from a file is not ideal, but the plan is for it to come from a database in the future. Libr ...

The leaking of angular-material CSS onto other divs is causing unexpected styling

I am having trouble incorporating Angular Material's md-autocomplete into my angular application. I have already customized the CSS being used in my application, but when I add the Angular Material CSS, it messes up the entire page. Even when I tried ...

The persistent problem with constantly polling the $.ajax request

One issue I'm facing involves a continuous polling $.ajax request. The challenge lies in initiating it immediately first, and then running it at intervals set in the setTimeout call. Take a look at the example code here. myObj = {}; var output = ...

Guide to centering Embed horizontally with Bootstrap 5

My goal is to create a centralized input with an image positioned above it. I have been following the guidelines provided in the position documentation, but the image still does not align horizontally: https://i.sstatic.net/awWxL.png Here's the code ...

Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way: .foo { transform: rotateX(-30deg) rotateY(35deg); } Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple: var matrix = $('.foo').css('tr ...

When attempting to change an image using JavaScript, the image fails to load

I am having trouble understanding what is wrong with my code. <html> <body> <script type="text/javascript"> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { ...

Check for the presence of a horizontal scrollbar on the page for both computer and mobile devices

Is there a way to determine if a web page has a horizontal scrollbar using jQuery or pure JavaScript? I need this information to dynamically change the css of another element. I initially tried function isHorizontalScrollbarEnabled() { return $(docum ...

Saving the output of a function in Javascript/NodeJS to a variable

I've been attempting to save the output of a function into a variable, but it's not working as expected. I've exhausted all my ideas and possibilities. Perhaps I'm just making a silly mistake :D I'm working with NodeJS, using expre ...

Close the material-ui popper when clicking away

I am currently working on implementing a Material UI popper feature that should close when the user clicks outside of it using ClickAwayListener. However, I have been unable to make this functionality work despite trying different approaches. I've att ...

Showing a div with 2 unique data attributes - such as displaying Currency and Quantity

My E-Commerce website is created using HTML, JavaScript, and PHP. On the product details page, users can add products to their cart, so I show the total cart value. I need the total amount displayed in a decimal number format (10,2). Currently, when a u ...

Utilize the Tab key in Textarea fields to insert a tab character ( ) instead of navigating to the

My current issue involves utilizing an HTML textarea named userInput. Whenever I press the tab key, it simply shifts focus to the next element instead of inserting a tab character or some spaces within the textarea. Is there a way for me to configure the ...

Facing delays in receiving responses for inner loop in node.js

Having an issue with retrieving data from the inner loop, as there is a delay in getting it. In my code, I am fetching the user list along with their ancestors from the SQL table. The ancestors are needed to verify their root values in the hierarchy/tree ...

Finding the right property by comparing it with an array of objects in a MongoDB aggregation query

In my mongoDB collection, I have a field called 'abc' that contains an array of objects structured like this: 'abc': [{"_id": new ObjectId("someId"), "name": "entity name"}] I am looking to perfo ...

Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query: // customers.model.js CUSTOMERS.getAll = (result) => { let query = "SELECT * FROM custo ...

What is the best way to open a link contained within a div by clicking on it

I am currently in the process of developing a website that is able to parse a Spanish dictionary. When looking up the word HOLA, the site provides the definition. However, for other words like CASA, users receive suggestions with links such as My goal is ...

How to ensure the priority of props.className in CSS-in-JS implementations

It is important for our components to prioritize the class passed as props over the default class. When passing classes as a prop, it is crucial for the component to give precedence to the class defined in its own file. Text.jsx // The following compo ...