``To enhance the scrolling functionality, dynamically apply a specific class when the page has reached

I am currently working with a piece of code that dynamically adds and removes the classes .nav-down and .nav-up to #nav based on the user's scrolling behavior.

jQuery(document).ready(function($){
  var didScroll;
  var lastScrollTop = 0;
  var delta = 5;
  var navbarHeight = $('nav').outerHeight();

$(window).scroll(function(event) { didScroll = true; });

setInterval(function() {
  if (didScroll) {
  hasScrolled();
  didScroll = false;
  }
 }, 150);

function hasScrolled() {
  if($( window ).width() > 768) {
  var st = $(this).scrollTop();
  if (Math.abs(lastScrollTop - st) <= delta)
    return;

  if (st > lastScrollTop && st > navbarHeight ) {

    // Scroll Down
    $('#s-nav').removeClass('nav-down').addClass('nav-up');

} else {

    // Scroll Up
    if (st + $(window).height() < $(document).height()) {
        $('#s-nav').removeClass('nav-up').addClass('nav-down');
    }
 }

} else {
$('#s-nav').removeClass('nav-up').addClass('nav-down');
}
lastScrollTop = st;
}
});   

My goal now is to include an additional class called .extra to #nav when the function adds .nav-down to #nav. However, I only want this extra class to be added when the user is at the top of the page, and not at any other point. This means it should only be added when the user is at the very top of the page.

Answer №1

Take a look at the jQuery documentation for more information on scrollTop(). When you reach the top of the page, the value is 0, so you can create a script to add a class when $(window).scrollTop() equals 0 and remove it otherwise.

Here's an example:

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

    if (scroll === 0) {
        $(".clearHeader").addClass("darkHeader");
    }
});

You can adjust this code as needed.

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 utilize jquery's $.ajax function in conjunction with json and php to upload a file?

Can someone assist me with uploading a file using jQuery's $.ajax function? I am not getting any output and I'm unsure if my script is correct. Here is the code: $.ajax({ url:'newsup.php', data: "", type: 'POST', cont ...

Loop through a JSON object to dynamically update the value of a specific key

I have a JSON object with keys and values, where some of the values are empty strings. I want to replace those empty values with the corresponding key name. However, when trying to get the value of a key within the loop, it returns undefined. JSON: "Forg ...

"Enhancing Your Website Navigation with jQuery: Incorporating Mouse Events into Your Menu

My objective is to create a simple mouseover effect on my menu that remains active while the mouse is in a submenu, and triggers the close() function when the mouse leaves the main tab or the submenu. I understand that an event handler is required to trig ...

What steps can I take to prevent the div from exiting the screen during animations?

Hello, I am a novice in the field of web development and I am attempting to create a website where, upon loading it, a text with a typing animation will appear centered in the middle. Eventually, the remaining words in the div will be 'Nice Paws' ...

Addressing the issue of MVC form authentication expiring during an ajax request

Within my MVC3 application, I encounter scenarios where a splash screen is displayed dynamically while loading partial views using jQuery's ajax functions to inject HTML into the DOM. The issue arises when user authentication expires and an ajax call ...

An issue occurred while evaluating the Pre-request Script: Unable to access the 'get' property of an undefined object

I need help accessing the response of my POST request in Postman using a Pre-request Script. Script below : var mobiles = postman.environment.get("mobiles"); if (!mobiles) { mobiles =["8824444866","8058506668"]; } var currentMobile = mobiles. ...

Update only one field at a time using the REST API

Currently, I am developing an inline grid editor that triggers a call to an express rest api whenever a user updates a single value in the grid. The issue I am facing is that when a field is changed, my PATCH request attempts to update all fields instead o ...

Generating Random Numbers Using Python and JavaScript Pseudo-Random Number Generation Algorithm

I am seeking a means to produce an identical series of pseudo-random integer numbers using both Python and JavaScript. Upon seeding in Python as shown below, I obtain the following outcomes: random.seed(3909461935) random.randint(0, 2147483647) = 1620 ...

Updating the Keycloak token in VueJS using keycloak-js even when it is still valid

I have implemented a VueJS frontend connected to Keycloak using keycloak-js openid, without using the implicit flow https://i.sstatic.net/BxhJh.png Currently, there is a scenario in which the Backend NodeJS adds groups to a user in Keycloak. However, in ...

Guide on detecting and capturing a change in location history event

My main goal is to capture router change events outside of the NextJS framework, not within it. The application I have developed using NextJS includes some code that operates independently of the NextJS context. This code needs to be able to detect navigat ...

Iterating through an array step by step in NodeJS with a delay before processing each element

I have a set of instructions stored in an array that must be executed in a specific sequence: const commands = [ `git clone https://github.com/EliLillyCo/${repo}.git`, `cd ${repo}`, `git checkout -b ${branch}`, 'cp ../codeql-analysis.yml .github ...

Using JavaScript to inject PHP variables into multiple <span> elements

I have been searching for a similar query without any luck. Currently, I am attempting to display the number of Twitter/Facebook/RSS followers within a <span>....</span> in my sidebar. To retrieve the follower counts, I am using some PHP scrip ...

Using React.js to dynamically render routes with components based on JSON data

As a newcomer to react and the world of JavaScript, I find myself facing a challenge. I have a JSON file that contains URLs which I want to use in rendering specific components. { "MTs": { "MenuItems": { "Main": { "key": "1", "u ...

When multiple instances of a Vue Filepond component are used on the same page, the input event emitter is saving the data in the v-model of the last

A new file-uploader component has been developed with the following setup: <template> <div> <file-pond :id="id" :key="id" name="files" ref="pond" v-bind="$attrs" v-on:activatefile="onActivateFileCli ...

Mapping an array of objects to an array of Q promises: A step-by-step guide

I am struggling to comprehend this issue. I have a list of positions that I need to convert into an array of promises and then collect them. However, the problem is that positionPromises ends up as an array of nulls ([ null, null ]) var positionPromises ...

Should you use Json or HTML? How can you distinguish between the two?

I have a scenario where my controller can return either JSON data or partial HTML based on the user's login status. After receiving the response, I need to distinguish between the two types of data. What would be the most efficient approach? In my c ...

The MaterialTable component is indicating that there is no property called 'tableData' on the IPerson type

Incorporated an editable attribute to my MaterialTable component. Currently looking for a way to retrieve the index of updated or deleted items within the onRowUpdate and onRowDelete methods. To replicate the issue, refer to this minimal sandbox example: ...

Exploring the relationship between two collections in Meteor, specifically using MongoDB for querying by value

Currently, I am developing a social media platform similar to Twitter but have encountered an issue with sorting. Below are the collections I am working with: Tweets: createdAt: Date body: String userId: String Events: createdAt: Date ...

jQuery effects failing to run properly in Internet Explorer

<script type="text/javascript" src="css/jquery-1.7.1.js"></script> <script type="text/javascript"> function slidedown(id){ $('#rerooftext').hide(0); $('#inspectiontext').hide(0); $('#remodelingtext').hid ...

Tips for dynamically adjusting the style of table rows in a v-for iteration:

I'm trying to dynamically change the background color of a table row within a v-for loop based on a condition - if global.globalGroupLevel is equal to 0, I want the background color to be one color, and if it's not 0, I want it to be another colo ...