Is it possible to determine the number of pixels scrolled from the current position on the page, rather than just from the top

I am looking to implement a standard UX feature that involves changing an element on scroll. Currently, I have this jQuery code in place:

$(document).scroll(function() {    
    var scroll = $(document).scrollTop();
    if (scroll >= 50) {
        $(".search-bar").removeClass('open');
        $(".search-bttn").removeClass('close');
    }
});

While this code works well and changes the classes after scrolling 50px from the top of the document, I am wondering if it is possible to achieve the same effect after scrolling 50px from anywhere on the page?

The reasoning behind this design choice is that I have a position:fixed search bar that appears when a click function opens it, and then I want it to disappear upon scrolling. However, I don't want it to vanish after just one or two accidental scrolls as it's easy to do so unintentionally. Ideally, I'd like it to only be removed after a significant scroll of around 50 pixels.

I hope this explanation makes sense! Any insights on how to achieve this would be much appreciated...

Cheers!

Answer №1

After triggering a click event, you can save the current scroll position and compare it to the new scroll position when scrolling.

var oldScrollposition = 0;
$("#CustomClickControl").on("click",function(){
  $(".search-bar").addClass('open');
  oldScrollposition =  $(document).scrollTop();
});

$(document).scroll(function() {    
    var scroll = $(document).scrollTop();
    if(scroll < oldScrollposition )
      scroll = oldScrollposition -scroll; // If scrolling down
    else
      scroll = scroll - oldScrollposition; // If scrolling up

    if (scroll >= 50) {
       $(".search-bar").removeClass('open');
       $(".search-bttn").removeClass('close');
    }
});

Remember to adjust the click control ID to fit your needs.

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

TypeScript error: Cannot find property 'propertyName' in the 'Function' type

I encountered an issue with the TypeScript compiler when running the following code snippet. Interestingly, the generated JavaScript on https://www.typescriptlang.org/play/ produces the desired output without any errors. The specific error message I recei ...

Invoking webservices repeatedly within a loop will not trigger the custom OnSuccess function

Currently facing an issue while coding in VS2008 where I am calling webservices from my JavaScript Page. For instance: Services.ChangeDropDownLists.GetNowPlayingMoviesByLocationSVC( blah, OnSuccessMoviesByRegion, OnError, OnTimeOut ); A ...

Retrieving the first five rows from a table with data entries

My task involves working with a table named mytbl, which contains 100 rows. I need to extract only the first five rows when a user clicks on "Show Top Five." Although I attempted the following code, the alert message returned 'empty': var $upda ...

The spinning wheel goes round and round while executing the location.reload() function

Currently, I am performing actions in my JavaScript function and then triggering a page refresh using location.reload(); I'm wondering if there is a straightforward method with jQuery to display a spinning wheel from the moment the page initiates the ...

The "maxlength" attribute does not function with the input type "number" in an HTML textbox

The maxlength attribute does not seem to be functioning properly when using type="number" ...

Error message "Function not defined while attempting to update ajax synchronization"

I have been working on converting a function that previously used to load synchronous ajax requests to getDesign.php. This PHP file requests some images which are then displayed on the screen using the loadImages function. Before the change, the code look ...

Activate/Deactivate Interactive Flot Chart

As a newcomer to jQuery, I am seeking assistance with an issue related to a dynamic graph created using jQuery and Flot. The graph is very similar to the one demonstrated in the following example: The adjustments I made to the code were primarily aestheti ...

Learning the process of obtaining tags through the utilization of the tag-it jQuery plugin

I'm currently using the tag-it jQuery plugin for a project I'm working on. However, I am facing an issue where I am unable to retrieve the tags that were entered in the text area as I keep getting an empty string. Here is the code snippet I am wo ...

Encountering a '[BABEL] Cannot find module' error message after setting up a new PC

Recently, I configured my development environment on a fresh operating system. When I navigated to my project folder and executed the commands: npm install npm run serve I encountered the following error message: Module build failed (from ./node_modules ...

What is the best way to share only specific json data from my php/mysql database, rather than displaying all

My code is functioning well, except that it's displaying all PHP results instead of just the specific json_encoded data I want. The following PHP retrieves data from my database: <?php session_start(); $_SESSION['charname'] = 'Egaht ...

Is there a smooth and effective method to implement a timeout restriction while loading a sluggish external file using JavaScript?

Incorporating content from an external PHP file on a different server using JavaScript can sometimes be problematic. There are instances where the other service may be slow to load or not load at all. Is there a method in JavaScript to attempt fetching th ...

Pass back the success/failure flag through ajax from a php script

As a novice coder, I've been struggling with a task for days now. Despite my efforts to search Google and Stack Overflow, I haven't found a solution that I can easily understand. The issue at hand is related to a Twitter Bootstrap landing page w ...

JavaScript onclick event triggers only the second audio to play

Does anyone have experience with adding sound effects to a website? I'm attempting to have a positive sound play when the correct image is clicked and a negative sound play when the wrong image is clicked. However, regardless of which image I click on ...

Angular Satellizer causing issues with Facebook login on mobile devices

Issue Currently, I'm developing an application using Angular and have successfully integrated Facebook login through Satellizer. The functionality works flawlessly on desktop browsers; however, when accessed from mobile devices, it tends to be unreli ...

problem with integrating ajax and php with jquery's datepicker UI

Trying to utilize the jQuery datepicker feature to select a date and then perform a select query from the database based on the chosen date. After some research, I came across this resource jQuery datepicker with php and mysql which suggests using ajax ...

Creating a non-intrusive modal in Bootstrap 4 that maintains background visibility and scrolling functionality

I have been working on creating a Bootstrap modal that allows the user to interact with the rest of the website while it is visible. The steps I have taken so far include: Adding data-backdrop="false" to the modal div in order to hide the shadow of the b ...

Difficulties encountered while trying to set up a multi-level list for a mobile

Trying out a tutorial to create a mobile dropdown menu. Encountering an issue when adding new lists inside a previous tag affects the functionality of the dropdown menu. Attempted to adjust the CSS without success. All the lists are displayed without req ...

Despite setting the date format in the Html Helper, the MVC still presents a validation error

When creating a razor view form to display the date field, I am using the following code: @Html.TextBoxFor(m => m.LectureDate, "{0:dd/MM/yyyy}") The desired date format is 21/04/2017, which is set by JQuery DatePicker. However, after setting the date ...

Using jQuery to populate an array and add commas to a mailto link

My issue involves a list of PDF links where users can select multiple options using checkboxes. When the form is submitted, it triggers an email (using mailto:) containing the selected items. Although everything is functioning correctly, there is one prob ...

The size attributes on <img> tags do not function as expected

I'm facing an issue with the following code: $("#myId").html( "<img src='" + $(xml).find("picture").text() + "' height="42" width="42"></img>" ); Everything works perfectly until I include the 'height="42" wid ...