Ways to identify when a person has scrolled a specific distance

Is it possible to modify the appearance of my top navigation bar once the page has been scrolled a specific number of pixels? I assume this requires some sort of listener to track the amount of scrolling. I came across element.scrollTop, but it doesn't seem to actively monitor the user's scroll progress.

What approach should I take to implement this feature?

Answer №1

Give this a shot:

window.addEvent('scroll',function(e) {
        if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
                // Add your code here
            }
});

Answer №2

Implement the following code snippet.

$(window).scroll(function()
{
    document.getElementById("fixed_box").innerHTML = "You have scrolled to " + $(window).scrollTop() + "px";
});
#fixed_box {
    position: fixed;
    top: 10px;
    overflow: auto;
    height: 100%;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div style="height: 5000px;">
</div>
<div id="fixed_box">You have scrolled to 0px</div>

Answer №3

window.addEventListener('scroll',handleScroll);

function handleScroll(){
      let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;

  if(scrollPosition >50)
      console.log('Viewport scrolled more than 50px')
  else
      console.log('Viewport scrolled less than 50px')

}

let optimizedHandlerScroll = debounce(handleScroll, 200);
window.addEventListener('scroll',optimizedHandlerScroll);

function handleScroll(){
        let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;
       if(scrollPosition >=50){
         console.log('more than 50')
       }
       else
         console.log('less than 50')
   }
   
   function debounce(fn, delay) {
      let timer = null;
      return function () {
        clearTimeout(timer);
        timer = setTimeout(function () {
          fn();
        }, delay);
      };
    }

The initial basic version is functional, but it can be resource-intensive. The scroll event handler gets triggered multiple times. On the other hand, the improved version in the gist only executes the handler once you finish scrolling, making it more efficient.

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

Activate the stripe button after successful bootstrap validation

My goal was to implement BootstrapValidator for validation on a couple of fields and enable the Stripe button only when both fields are valid. Currently, the button is enabled once any of the fields pass validation. The challenge lies in ensuring that the ...

Advanced data synchronization with Angular 7's bidirectional data binding feature

One input box allows users to enter a number, and I would like to adjust the width of the background color based on that number. The box itself will have a fixed width, but I am looking to dynamically change the width of the background color according to ...

Unable to successfully transfer JSON data from JavaScript file to .NET controller using AJAX POST request

I'm facing an issue where I am trying to send a JSON string from the client (js) to the server (.NET controller) using AJAX post. However, when the data reaches the controller, the list is empty with a count of 0, which is puzzling me. JS Code btnAd ...

Utilizing Firebase messaging onMessage function is exclusively enabled within a window environment

Incorporating Firebase Cloud Messaging into my project allowed me to send and receive push notifications successfully. While I can receive the push notifications, unfortunately, I am encountering issues with getting the notification events to function prop ...

I'm confused why this particular method within a class is not being inherited by the next class. Rather than seeing the expected extension, I am presented with - [Function (

Working fine with the Person class, the register() function displays the correct return statement when logged in the console. However, upon extending it to the Employee class, instead of the expected return statement, the console logs show [Function (anon ...

Using CSS or Bootstrap, align the image to the right side of the content

Struggling to align an image to the right of the content area, inspired by this Dribble shot. Check out the inspiration here This is what I've come up with so far: Link to my progress on CodePen .content { position: relative; } .bg-image { posi ...

Is it possible to capture and generate an AxiosPromise inside a function?

I am looking to make a change in a function that currently returns an AxiosPromise. Here is the existing code: example(){ return api.get(url); } The api.get call returns an object of type AxiosPromise<any>. I would like to modify this function so ...

Altering documents post Bower installation

I took the initiative to manually download the css and js files for an angular module (here). In order to make a small adjustment, I modified the css (specifically changing max-width in the media query): Original: @media only screen and (max-width: 800px ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

Obtaining select options in jQuery by utilizing the $(this) selector

Looking for a way to loop through and log each option available in a select dropdown box, but struggling with how to use $(this). This is the code I have so far: $('select').each(function(){ $(this).find('options').each(function() ...

Exploring data-toggle elements using jQuery

I am faced with the challenge of dynamically constructing a form using jQuery. The form includes a checkbox list of items that I am creating in the following manner: function initializeForm() { var html = ''; var items = GetItems(); for ( ...

Searching for specific text within HTML href tags involves parsing the HTML document and

[I'm having trouble isolating links that contain the specific text '/Archive.aspx?ADID='. Even though I have tried to filter for these specific links, I end up retrieving all of the links from the webpage. Once I am able to extract the desir ...

The jQuery .ajax() function encountered a 405 error stating "Method Not Allowed" when attempting a cross

Despite searching extensively on SO, I am unable to pinpoint the issue in my code. To avoid using JSONP, I am implementing CORS. I understand that this is a preflighted request and believe I have included the correct headers. The problem lies in the web ...

"Unlocking the power of AngularJS translate: A step-by-step

I'm seeking answers to two questions. 1) How can I utilize angularjs translate with ng-repeat? Although my Json file works fine, the text does not display when using ng-repeat. Here is a snippet from my json: "rules":{ "points":[ {"t ...

Troubleshooting problem in Vercel with Next.js 13 application - encountering "Module not found" error

Encountering a deployment issue with my Next.js 13 application on Vercel. I recently implemented the Parallel Routes feature of Next in my codebase. While pushing the changes to create a new pull request on GitHub, the branch's deployment on Vercel is ...

Is there any more Angular code to be bound using ng-bind-html or ng-bind?

Hey there! Just a quick Angular inquiry: <div class="_minimal_size margin_10_middle"> <div class="_50 espaciado_0_20"> <p ng-bind-html="eirana_knows.feedback"></p> </div> <br class="clear"/> </div ...

Include vue-videobg in Vuetify using CDN without the need for webpack

I am trying to integrate vue-videobg into vuetify using a CDN without any additional requirements like "magic_videobg_to_install.java.css.js.htm" <!DOCTYPE html> <html> <head> <link href="https://fonts.googleapis.com/css?family=R ...

Use a conditional statement for each element within the array

Below is the code I am currently using: if (res[0].toString() == "hello") { res[0] = "string"; }; While it works, I would like this logic to apply to all elements rather than just the first one. Is there a way to achieve this for every element in the ar ...

Transferring an Applescript list to ExtendScript in Javascript as an array for use in InDesign

Situation Background I have a large number of Applescripts (AS) that designers rely on in InDesign to streamline production workflows. These AS scripts handle a lot of OS interactions that JavaScript cannot replicate, so transitioning away from AS is not ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...