Is it possible to eliminate the sticky class as you scroll down?

Check out this jQuery code I wrote to remove the sticky class while scrolling down:

$(window).scroll(function (e) {
    if ($('.main_form_wrapper').length != 0) {
        var window_scroll = $(window).scrollTop();
        console.log(window_scroll, "current window scroll position")
        var bottom_position = window_scroll + $('.main_form_wrapper').outerHeight(true);
        console.log(bottom_position, "position of main form wrapper at the bottom")
        var form_top_offset = $('.main_form_wrapper').offset().top;
        console.log(form_top_offset, "offset of main form wrapper from the top")
        var footer_top_offset = $('.top_footer').offset().top;
        console.log(footer_top_offset,"offset of the top footer")
        if (window_scroll > form_top_offset &&  bottom_position < footer_top_offset) {
            $(".main_form_wrapper").addClass('sticky'); 
        } else {
            console.log('reached end')
            $(".main_form_wrapper").removeClass('sticky');  
        }
    }
});

If anyone can offer some guidance, that would be greatly appreciated!

Answer №1

This content is loosely based on a similar post about Detecting scroll direction.

Here's an example I put together for you. The key point to note is the importance of storing the last scroll position in order to determine whether the user is scrolling up or down:

var lastScrollTop = 0;
var theWrap = $('.wrap');
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // Code for downward scroll
       theWrap.removeClass('sticky');
   } else {
      // Code for upward scroll
       theWrap.addClass('sticky');
   }
   lastScrollTop = st;
});
.wrap {
  width: 100px;
  height: 2000px;
  background-color: orange;
}
.wrap.sticky {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap sticky">

</div>

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

Retrieve the heading of a click-able element using jQuery

My challenge involves a list of selectable buttons with names generated dynamically from a JSON file. Each time a button is clicked, I aim to retrieve its title, which corresponds to row["name"]. Below is my relevant code snippet and the JSON data provided ...

What is the best way to locate and extract the content of an HTML element using XPath in Selenium with VBA?

I am currently seeking a solution to extract the content of an element with the name "data-testid" from a website. This specific element appears approximately 35 times within various contexts in the HTML code. The particular element I am interested in look ...

Implementing Object Value Assignment to an Element Using jQuery

I recently received a set of data via an API request: https://i.stack.imgur.com/YGe2D.jpg In order to display this data as selectable options, I included the following code snippet in my AJAX script: $.each($(value.routes), function(index, route){ $ ...

Is there a way to incorporate a fade-in effect when I trigger the expand function in this script?

I recently came across a jQuery plugin for expanding and collapsing content. I am interested in adding a fade-in effect to this plugin specifically when the EXPAND button is clicked. How can I accomplish this? $(document).ready(function () { var maxlines ...

How to rotate text direction using JavaScript and CSS

Despite my extensive efforts, I have been unable to find a solution to a seemingly simple problem. In JavaScript, I have generated dynamic text using the following code: context.fillText('name', 10, 10, 20); Now, I need this text to be ori ...

Ways to customize the color of a ReactSelect component?

Hey there! I'm currently utilizing the React select component, with the following import statement: import ReactSelect, {ValueType} from 'react-select'; Here is what my component currently looks like: https://i.stack.imgur.com/yTmW4.png Th ...

The chosen element contains a value of -1

When the select element has a selected value of 4, form data is sent to the server and the controller returns a partial view. <script> $(document).ready(function () { var objSel = document.getElementById("IDVacationApplicationTyp ...

When using the jQuery ajax function to validate a form, it is important to note that the $_POST variables

I have an HTML form along with a jQuery function for form validation. After submitting the form values to my PHP files, I notice that the $_POST variable is not being set. What could be causing this issue? <form id="signup" class="dialog-form" action= ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...

Even after dynamically removing the class from the element, the Click event can still be detected

My buttons have a design like this: <a class="h-modal-btn branch-modal-btn"> Buy Now </a> The issue arises when I need to remove certain classes and add attributes to these buttons based on the query string in the URL. Skipping ahead ...

Switching the background image upon hover while incorporating a subtle fade transition in HTML and CSS

Is there a way to set two background images on a div and have them change when hovering with a fade effect? Similar to the example shown. .kid { max-width:50%; position:relative; } .kid img { display:block; opacity:1; height: auto; transition:.6s ease; ...

Initiate the execution of JavaScript functions in the loaded partial view using Ajax

I am currently working with a javaScript function that loads a partial view within my page's layout using the following logic: $('.follow-tasks').click(function (e) { e.preventDefault(); var $followtaskList = $("#td-" + $(this).attr ...

What is the best way to send HTML tag content to mark.js and delimit them with a space or comma?

I have been utilizing the mark.js library to highlight keywords on a webpage, and it's been working well. However, I now need to insert an extra space or a comma after each tag such as h1, h2, etc. Initially, I thought about using a loop like the one ...

Centered content appears smaller than the surrounding div

After spending an hour trying to troubleshoot and searching for solutions, I am turning here for help. I am attempting to insert a Bootstrap Nav-Bar into a Div. I successfully centered the Nav-Bar, but now my Div is taller than the content inside it. This ...

Retrieving the checkbox's status from the database

I have implemented a basic checkbox that updates its state in the database when clicked or unclicked. Is there a way to retain this state and have it displayed as checked if the page is refreshed? Essentially, I want the checkbox to remember its last state ...

Proper method for posting an object array through a form submission

I am currently integrating a payment service API into my application and following the instructions provided on their website. The documentation specifies that the POST body should have the following structure: api_hash=38be425a-63d0-4c46-8733-3e9ff662d62 ...

Tips for adjusting the font size options within the Autocomplete feature of Material UI Version 5

Is there a way to adjust the font size of the drop-down items? I have tried various methods to change the font size, including: How do I change Material UI Autocomplete font size? How to change fontsize of options in Material ui autocomplete? Unfortuna ...

Which UL should be selected next?

I am facing an issue with a trigger that is meant to target the next UL element and apply effects to it. <div id="archives_trigger"><a class="menu_trigger">Monthly Archives</a></div> <ul id="archives_menu"> <?php wp_ ...

Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

What is the best way to ensure that these social icons are perfectly centered on the page across all web browsers?

Visit my website here: foxweb.marist.edu/users/kf79g/contact.php I'm stuck on the final step needed to deploy my website and finish it. The issue I'm facing is with the social icons when viewed on medium and small screens. I want them to be cent ...