Adjusting the height of an element as you scroll will activate the scroll event

One issue I'm facing is with adding a class to my header. The goal is to reduce the height of the top part of the header when the user scrolls down and then remove the class when they scroll back up. While this functionality is working, there is an unexpected behavior where the class is added and removed continuously, most likely due to the continuous firing of the 'scroll' event triggered by the height change.

$(function() {
  const $header = $('header');
  let prevScroll = 0;
  
  $(window).scroll(function() {
    let scroll = $(window).scrollTop();
    if (prevScroll - scroll > 0) {
      $header.removeClass('scrolled-down');
    } else {
      $header.addClass('scrolled-down');
    }
    prevScroll = scroll;
  });
});
.container {
  position:relative;
  width:90%;
  margin:0 auto;
}

header {
  position:sticky;
  top:0;
}
  .top-header {
    background:blue;
    height:50px;
    transition:all .5s;
  }
    header.scrolled-down .top-header {
      height:10px;
    }

  .nav-header {
    background:red;
    height:100px;
  }

.body-content {
  min-height:1500px;
  border:1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <header>
    <div class="top-header"></div>
    <div class="nav-header"></div>
  </header>
  <div class="body-content"></div>
</div>

Answer №1

If you're looking to change the height of an element in order to adjust scroll position, it's important to consider the header's height before and after scrolling. By coding a function based on these heights, you can achieve the desired effect of pinning a small header at the top of the viewport when the user scrolls to the bottom. Here is some code that may assist you with this:

$(function() {
  const $header = $('header');
  let headerHeight = 160,
      headerSmallHeight = 60;
  
  $(window).scroll(function() {
    let scroll = $(window).scrollTop();
    
    if (scroll === 0) {
      $header.removeClass('scrolled-down');
    } else if(scroll > headerHeight) {
      $header.addClass('scrolled-down');
    }
  });
});

I hope this information proves helpful to you in achieving your desired functionality.

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

jQuery text replacement formatting

I need to strip parentheses and spaces from a field retrieved from JSON data. My initial approach was: '+myleads.Phone.replace(/(/g,'')+' However, repeating this process for each replacement seems cumbersome. Is there a simpler solut ...

Mastering the use of Quasar variables in your scss styles is crucial for optimizing your

I recently set up a project using Vue3 and Quasar by running vue add quasar. However, I am struggling to figure out how to utilize Quasar sass/scss variables. According to the documentation, I should use the following syntax: <style lang="scss&quo ...

Is there a way for me to delay sending an immediate response until the asynchronous loop has completed?

Currently trying to implement something similar to the code snippet below. I suspect that the issue lies within the asynchronous call as it seems like the response I am getting is always an empty array, despite the API returning data. As a beginner in th ...

The anchor tag dwarfs the element it contains

I'm experiencing an issue on my website where the clickable area of my two images/buttons, labeled Get Started and Learn More, is larger than the actual image itself. I've wrapped the images with anchor tags to link to separate pages, but for som ...

Problem encountered when transferring JSON data to PHP for file writing

After spending numerous hours researching potential solutions, I still can't seem to fix the issue at hand. Admittedly, I am fairly new to PHP, so it's possible that I am overlooking a small detail. The problem lies in the fact that I have a form ...

Callback not being triggered after AJAX request

I am currently troubleshooting some code that was not written by me, and I am facing challenges in understanding why an Ajax return is not triggering a Callback. The following code is responsible for attaching behaviors to the ajax functions: # Callback ...

When using the <Routes> component, it will not render a component that acts as a container for multiple <Route> elements

Upon wrapping my component in <Routes>, I encountered this warning: Warning: [Categories] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment> In App.js: const App = () => ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

Implementing an array of objects within a Vue method

I currently have an object called "Sorteio" which contains a vector of objects named "Resultado", consisting of 6 Resultados. The way I am creating instances of them is as follows: saveSorteio() { var data = { loteria: this.sorteio.loteria, ...

Prevent multiple sliding menu animations - .stop()

I'm encountering a problem with my sliding menu (3 levels). When I quickly move the mouse over the menu, it ends up sliding up and down multiple times. I've heard that using the jQuery function .stop() can fix this issue, but I'm not sure h ...

Looking for CSS templates for improving your business web apps?

Many CSS templates out there are fixed-width, typically around 900 pixels wide... Right now, I'm in the process of creating an intranet Rails application and I'm seeking a good resource for CSS templates designed specifically for business applic ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

Error encountered while attempting to make AJAX call: "`$.ajax` parse error on JSON object: {"vErrorsFound":true,"vMessage"

I am trying to update my code from using jQuery 1.3.2 to jQuery 1.5, but I am facing issues with parsing JSON data. I have a PHP script that returns the following JSON object using json_encode: {"vErrorsFound":true,"vMessage":"Login Failed"} I have exper ...

Is it possible to modify the appearance or behavior of a button in a React application based on its current state?

I'm looking to customize the color of a button based on different states. For example, if the state is active, the button should appear in red; otherwise it should be blue. Can anyone suggest how this can be achieved in React? Furthermore, I would als ...

Adding items to a jCarousel using C# programming language is a simple process that involves following

I am struggling to display images in jcarousel using a C# Webmethod and jQuery Ajax. Here is my setup: My HTML structure: <div> <ul id="mycarousel" class="jcarousel-skin-tango" style="float: left"> </ul> </div ...

Update the href attribute with values from the form fields

My current project involves creating a form with 5 input fields: Service type Number of days Number of children Number of adults I want to dynamically change the value of a button based on these variables using JavaScript. Here is my code so far: JS ...

An error message is displayed when attempting to retrieve a json response

After implementing my flask app, I noticed that the following code snippet is being returned: return json.dumps({'status': 'OK','url': 'www.blahg.com'}) Upon inspecting my javascript code, I found it to be structur ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

When decoding a JWT, it may return the value of "[object Object]"

Having some trouble decoding a JSON web token that's being sent to my REST API server. I can't seem to access the _id property within the web token. Below is the code I'm currently using: jwt.verify(token, process.env.TOKEN_SECRET, { comp ...

What is the best way to access data from outside a forEach loop in JavaScript?

I am trying to access the value of my uid outside of the foreach loop in my code. Can anyone assist me with this? This is the code I am working with: var conf_url = "https://192.168.236.33/confbridge_participants/conference_participants.json?cid=009000 ...