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

Adjust header display for smaller screens

Looking for help with adjusting my header design on small screens: I want the search bar to go underneath on smaller screens, like this example: I've tried changing the position to relative at a certain screen width but it didn't work. <di ...

What is the best way to remove jest from your system completely?

I've been trying to set up jest for testing react applications However, after installing it with yarn, I am encountering issues starting my react app in any way This error message keeps popping up, but the suggested solution didn't resolve it: ...

Error: Unable to access the 'name' property of an undefined variable

When running the code, I encountered a "TypeError: Cannot read property 'name' of undefined" error, even though when I console.log it, it provides me with the object import React from "react"; class Random extends React.Component { constructo ...

Can you explain the distinction between using destructuring syntax and an empty parameter when calling a render function?

After writing some code in React, I found using this.props to be too verbose. So, I researched some articles and learned how to approach this issue while coding. class MyComponent extends Component { // the traditional method render() { re ...

The positioning attribute and flexible height in CSS are essential for creating dynamic

My goal is to create a layout with 3 DIVs inside a container, similar to table rows. top {height = 100px} / middle {height = dynamic} / bottom {height = 100px} I am trying to figure out the best approach to make the height of the middle div dynamic whi ...

React developer server is failing to automatically refresh the code

I've encountered an issue with react-dev-server where changes I make to the code do not reflect on the app itself even after refreshing (not hot-loading). I've tried setting up my own project as well as using Facebook's Create-react-app, whi ...

DOMPDF struggles with rendering a font and instead displays circular shapes

After following the instructions in this guide: github.com/dompdf/dompdf/wiki/UnicodeHowTo I ran the load_font.php script, verified that the font files were successfully copied to /dompdf/lib/fonts, and ensured that the font information was added to the f ...

What is the process for allowing right-click to open in a new tab, while left-clicking redirects to a new page in the current tab?

In my project, I have implemented a multi-page form for users to input information. The left side menu contains items that allow users to switch between different pages while filling out the form. Currently, clicking on any of these items redirects the use ...

Create a custom VueJS component by utilizing an npm package

Looking to navigate around X-frame restrictions? You can check out this npm package: https://www.npmjs.com/package/x-frame-bypass To make it work, include the following tag within your HTML: <iframe is="x-frame-bypass" src="https://example.org/">& ...

Using express to efficiently redirect from a search form?

As a newcomer to this, my goal is to initiate an external API call after entering a term in a search form and then migrating to a new page displaying the outcomes. Here's what I have accomplished thus far. const express = require('express') ...

Creating a MySQL table that includes long string data types

Recently, I was working on creating an online forum and encountered a problem with the writing function. The form consists of a title and content section, which usually functions properly. However, when I enter a slightly longer text in the content field, ...

Div I add to page is not being styled by CSS

I'm currently developing a Chrome extension that provides a preview of a webpage when hovering over a hyperlink to it. To achieve this, I am creating a div and filling it with different items. However, the issue I'm facing is that the CSS styles ...

What is the best way to increase the height of a div up to a specific point before allowing it to scroll?

Is there a way to make a div expand to fit its contents up to 250px and then scroll if necessary? I attempted using the following CSS: text-overflow: ellipsis; max-height: 250px; overflow-y: scroll; However, this solution doesn't achieve the desired ...

How can I retrieve information from an HTML or JavaScript object?

Imagine a scenario where you have an HTML table consisting of 5,000 rows and 50 columns, all generated from a JavaScript object. Now, suppose you want to send 50 checked rows (checkbox) from the client to the server using HTTP in JSON format. The question ...

Transferring PHP array data into JavaScript array values

A PHP array structure is presented below. Array ( [0] => hal([[br,1],[cl,4]]) [1] => alk([[nc(1),1,2],[nc(1),3]]) ) I need to convert this array into JavaScript format like so: var hal=[["br",1],[cl,4]]; var alk=[[nc(1),1,2],[nc(1),3]]; In ...

Retrieving ng-model using ng-change in AngularJS

Here is an example of the HTML code I am currently working with: <select ng-model="country" ng-options="c.name for c in countries" ng-change="filterByCountry"></select> This HTML snippet is being populated by the following object containing a ...

AngularJS Object Comparison: A Comprehensive Guide

My form initiates a GET request to the server upon loading, receiving data that is stored in 'master' and then copied to 'local' as shown below. $scope.dirty = false; init(data); function init(data) { $scope.master = angular.copy ...

What steps can be taken to enable JSONIX to handle additional XML elements during the deserialization process?

JSONIX 2.0.12 is truly impressive. I am working with a substantial XML file and I am only looking to convert certain elements into JSON format. Whenever I omit some elements from my mapping file, JSONIX throws an unexpected element error during deseriali ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

The functionality of BASE64 encoding in HTML appears to be malfunctioning

I have exhausted all options in my attempt to display an image using a base64 string, but none of them seem to be working. I have tested it on IE6,7, Firefox 3. Can someone please point out what is wrong with the code below? <head> <STYLE type ...