When the user reaches a specific point while scrolling, apply a class to the element

I've successfully implemented a sticky header using jQuery, adding a class to the header when the user scrolls past it. Now, I'm wondering how I can include an additional class to the header when the user is scrolling back up and gets within 50px of the top of the page. This extra class should only be added when the user is scrolling upwards, not downwards, and should be removed once the user reaches the very top of the page.

Here's the code I currently have:

$(window).scroll(function () {
    if( $(window).scrollTop() > $('#header').offset().top && !($('#header').hasClass('sticky-header'))){
            $('#header').addClass('sticky-header');
        } else if ($(window).scrollTop() == 0){
            $('#header').removeClass('sticky-header');
            }
    });

Answer №1

Here is a suggestion to enhance your code:

let previousScrollPosition = 0;
$(window).scroll(function () {
let currentScrollPosition = $(this).scrollTop();
if ($(window).scrollTop() > $('#header').offset().top && !$('#header').hasClass('sticky-header')){
    $('#header').addClass('sticky-header');
}
// The following code hides the class when the user scrolls down by more than 500
if (currentScrollPosition > previousScrollPosition) {
    if ($(window).scrollTop() > 500){
        $('#header').removeClass('another-sticky-header');
    }
}
// This part of the code adds a class when the user scrolls up before reaching 500 pixels
if (currentScrollPosition < previousScrollPosition) {
    // You can adjust the value from 500 to any other number depending on your desired effect
    if ($(window).scrollTop() < 500){
        $('#header').addClass('another-sticky-header');
    }
}
if ($(window).scrollTop() === 0){
    $('#header').removeClass('sticky-header');
    $('#header').removeClass('another-sticky-header');
}

previousScrollPosition = currentScrollPosition;
});

Note: There are opportunities for code optimization, such as using ternary operators and combining certain if conditions. I suggest exploring these optimizations for better efficiency.

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

What is the best way to implement a Fibonacci sequence using a for...of loop?

**Can someone show me how to generate Fibonacci numbers using the for...of loop in JavaScript?** I've tested out the following code and it's giving me the desired output: function createFibonacci(number) { var i; var fib = []; // Initi ...

The issue with CSS z-index not functioning properly when using absolute positioning

Here is the issue I'm facing: I have multiple div containers in my code. .outer { position: relative; z-index: 1; } .inner { position: absolute; z-index: 999; } <div class="outer"> <div class="inner"> <div class="option ...

Sound did not play when certain pictures made contact with other pictures

English is not my native language and I am a beginner in programming. I know my explanation may not be perfect, but I'm trying my best to communicate my ideas clearly. Please be patient with me and offer constructive feedback instead of downvoting, as ...

Preventing the need to reset JavaScript text inputs

I'm encountering a strange issue in my code. I'm developing a graphing calculator that requires users to enter multiple expressions for evaluation. I have a text input and a button that adds a new input to the parent div whenever it is clicked: d ...

Using next.js to fetch data can result in an endless loop of API

This specific code snippet is taken from the Next.js documentation and can also be accessed through the following link: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating. However, when attempting to fetc ...

Seamless animated loading gif as a looping background visual

Is there a way to find a GIF that can be used as a repeated background on an HTML element, creating the illusion of a seamless block? https://i.sstatic.net/5BKxW.gif (source: opengraphicdesign.com) I am looking for an 80x80 GIF that can be repeated as ...

Inserting POST request data into subdocument arrays of a database

I am struggling to add data to a nested mongoose sub-document when creating a new schema from the client side. Only the data that is not nested inside another schema/array is being sent over to the database. My database setup includes MongoDB with Mongoos ...

Manipulating object attributes in three.js using WebGL

I'm currently working on animating a sphere with increasing radii. Below are the key parts of my code: function create_sphere(){ var sphereMaterial = new THREE.MeshLambertMaterial( { color: 0xCC0000 }); var radius=2,segments=50,rings=50; sph ...

Data within object not recognized by TableCell Material UI element

I am currently facing an issue where the content of an object is not being displayed within the Material UI component TableCell. Interestingly, I have used the same approach with the Title component and it shows the content without any problems. function ...

JQuery plugin for creating interactive date selection forms

Having some trouble creating a dynamic form. The datepicker seems to only work on the first row and I can't click it. Tried a few different codes but no luck so far. Below is the code excluding the PHP part, which is just for inserting into a database ...

Overlay displayed on top of a single div element

Trying to implement a loading overlay in an Angular project within a specific div rather than covering the entire page. Here's a Fiddle illustrating my current progress: #loader-wrapper { top: 0; left: 0; width: 100%; height: 100%; ...

Using jQuery to Retrieve Accurate User Identification - Making AJAX Requests

Currently, I am facing a bit of a dilemma. I have implemented 2 jQuery scripts to handle updating a simple database row based on user ID and session. This functionality allows users to send a "Gift" that adds value to their database row column "bonus". Wh ...

I am having trouble with my append function even though I checked the console log and did not see any errors (beginner's inquiry)

As I practice working with functions and dynamically creating input fields, I have encountered an issue where I am unable to append my input field to the form. Despite using console.log() and not seeing any errors, I can't figure out what mistake I ma ...

Generating elements added at various depths within an HTML document with the help of JavaScript

create_new.append("div") .append("form").merge(update_5) .attr("action", d => d.market) .attr("target","_blank") .style("width","100%") .style("height","282") .append("input").merge(update_5) .attr("type","submit") ...

A 'select all' checkbox in a PHP 'foreach loop' with JavaScript

I am in search of a solution to implement JavaScript in the given code block. My goal is to have the checkbox with id = alles automatically check all the checkboxes that are generated within the while loop. <form id="andere" name="andere" action="<? ...

Invoking Angular component method using vanilla JavaScript

For my web application, I am utilizing Angular and require Bluetooth functionality on a specific page. I am implementing loginov-rocks/bluetooth-terminal (https://github.com/loginov-rocks/bluetooth-terminal) for establishing the Bluetooth connection, which ...

Verify whether the input is currently being focused on

My current issue involves an input field that requires a minimum number of characters. If a user begins typing in the field but then switches to another without meeting the character requirement, I would like to change the text color to red. I attempted u ...

The dropdown in the Material UI GridList appears excessively wide

Currently, I'm attempting to design a grid-shaped drop-down menu in Material UI. Most of the dropdowns available in the documentation are either a single column or a single row. I tried utilizing a menu component that includes a GridList, which almost ...

I have noticed that the brand section of the navigation bar changes to black when I hover over it, but I have been unable to locate any

I'm currently working on a Rails application that has a navbar-top with a brand element. However, I've encountered an issue where the background of the brand element turns black when I hover over it. Despite inspecting the browser console, I coul ...

Integrate a variable called "counter" with the jQuery ID

I currently have the following code, which is functioning well. $('.clickable').click(function(e){ e.preventDefault(); $('#toggle').slideToggle(); }); $('.clickable1').click(function(e){ e.preventDefault(); $('# ...