How can I make an element begin sticking to the page at 50px when scrolling, and then stop sticking at 2000px?

I am looking for a solution to position an image relative or absolute initially, then make it stick after some scrolling, and finally return it to its original behavior before transitioning to another section on the page. I've tried using this script but it seems to conflict with itself:

<script>
jQuery(document).ready(function(){
window.onscroll = function() {
    if (window.pageYOffset <= 50){
        jQuery('.stickem').css({position: 'absolute', top: '50px' });
    }
    else {
        jQuery('.stickem').css({position: 'fixed', top: '50px'});
    }
    if (window.pageYOffset >= 2040){
        jQuery('.stickem').css({position: 'absolute', top: '2040px' });
    }
    else {
        jQuery('.stickem').css({position: 'fixed', top: '2040px'});
    }
}
});
</script>

I just need the "fixed" class to be applied when the scroll position is between 50px and 2040px. Is there a way to achieve that?

Answer №1

Consider giving this a shot:

jQuery(document).ready(function() {

    var fixedClassName = 'fixed';
    var absoluteClassName = 'absolute';
    var $window = jQuery(window);
    var $stickem = jQuery('.stickem');

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

        if (scrollTop > 2040) {

            if ($stickem.hasClass(fixedClassName)) {
                $stickem.removeClass(fixedClassName);
            }

            if (!$stickem.hasClass(absoluteClassName)) {
                $stickem.addClass(absoluteClassName);
            }

        } else if (scrollTop >= 50 && scrollTop <= 2040) {

            if (!$stickem.hasClass(fixedClassName)) {
                $stickem.addClass(fixedClassName);
            }

            if ($stickem.hasClass(absoluteClassName)) {
                $stickem.removeClass(absoluteClassName);
            }

        } else if ( $stickem.hasClass(fixedClassName) ) {

            $stickem.removeClass(fixedClassName);
            $stickem.removeClass(absoluteClassName);

        }
    });

});

If you'd like to experiment with the code, check out this fiddle link:
https://jsfiddle.net/rgvap3jh/

Feel free to customize the styling for the .fixed and .absolute classes according to your requirements.

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

jQuery ajax errors are slipping through the cracks and not being properly addressed

I'm struggling with the jQuery ajax success handler. I've noticed that any JavaScript errors that occur within the success handler are not being reported (no errors show up in the Firefox error console). This lack of error notifications is making ...

Having trouble getting the hover effect to change the colors of CSS borders

I am experiencing difficulty in changing the background color of the 'About' button to yellow and the border color to blue when it is hovered over. Currently, only a small rectangle around the text changes to yellow on hover and I cannot figure o ...

Error Styling: Using CSS to Highlight Invalid Checkboxes within a Group

Is there a way to create a bordered red box around checkboxes that are required but not selected? Here is the code I currently have: <div class="fb-checkbox-group form-group field-checkbox-group-1500575975893"> <label for="checkbox-group-15005 ...

Steps to import shared CSS using Styled-components

In my project using react, I've implemented styled-components for styling. One requirement is to have a shared loading background. Here is the code snippet of how I defined it: const loadingAnimation = keyframes` 0% { background-position: 95% 95%; } ...

Modify the initial value of various HTML elements

Recently, I encountered an issue with a HTML report that can be saved to a file and reopened. Upon reopening the file, there is a "Refresh" button available to update some information from the database. Visually, the refreshed content appears correctly, b ...

"Implementing a click event handler on a button within an iframe

On my website, I have embedded an iframe containing external content. Within the code of this iframe is a button identified by the id "XYZ." I want to create an onclick function for this button. Here's what I've attempted: $( "#XYZ" ).click(fun ...

Send form data without reloading the page and connect it to a JavaScript script

I've designed a system that reveals values based on a specific input selection. Below is the main form where users can enter model numbers and press enter: <form> <input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$" ...

Is there a way to dynamically insert the value of an input field into a text field in real time using Javascript or ajax?

In my form, there is a text field with the id #image_tag_list_tokens. It looks like this: = f.text_area :tag_list_tokens, label: "Tags (optional) ->", data: {load: @image_tags }, label: "Tags" Additionally, I have an input field and a button: <i ...

What is the best way to implement the nth:child selector in conjunction with the each function for handling JSON data in

Here is the HTML code I have written: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Flickr Feed</title> <link href="../_css/site.css" rel="stylesheet"> <link rel="stylesheet" type= ...

Exploring the functionalities of JSON and AJAX with a two-dimensional array

I have created a function to call JSON data, but it's not working. Any suggestions on how to properly call it? function fetchCompanyExpensesType(elementId){ $.ajax({ url: "../../modal/get_companyexpenses_type.php", dataType: ...

Tips for designing a form action

I am a beginner and struggling with understanding the CSS for the code below. Can someone help me out? <div id="page-container"> <?php include_once("home_start.php"); ?> <h1>Login</h1> <for ...

Transforming each element of an observable array by updating their properties with data retrieved from an ajax request using knockout

In my ViewModel "AppViewModel", I am fetching JSON data to create the model. One of the properties, "totalSessions", requires an ajax call to be fetched. While my code runs without errors, the view does not update as expected. var jsonapparray = []; ...

information not visible on the webpage

Recently, I made an alarming discovery on my website. I have implemented two different types of menus - one for the front page (designated as .navbar-inverse) and another for all other pages (.navbar-default). The front page menu is static while the other ...

Uniform selection frame width across nested list elements

I want to ensure that the width of the selection frame for all nested ul li elements is consistent, just like in this example. When hovering over an element (making the entire line clickable), I don't want any space on the left. Currently, I am using ...

Height transition animation in Angular 2 - maintaining state consistency

I am currently working with an animation code that is linked to my component. animations:[ trigger('slide', [ state('show', style({ height: '*' })), state('hide ...

Effortlessly Display or Conceal Numerous Table Columns Using jQuery

I have a small table where I want to hide certain details with a basic button... for instance, table { border-collapse: collapse; } th, td { border: 1px solid gray; padding: 5px 10px; } <button>Show/Hide Details</button> <table> ...

Looking for a vertical scrollbar solution for your idangerous vertical swiper?

Incorporating idangerous vertical swiper with two slides in a mobile app through jquery mobile has proven challenging. Specifically, I am struggling to implement a vertical scroll bar in the second slide due to its fixed height and the potential collision ...

A linear gradient effect originating from the center/middle of the background

Is it possible to create a linear-gradient background that starts from the center or middle of the screen? This is the CSS I am currently using: body { display: table; width: 100%; height: 100%; margin: 0 auto; background-repeat: no-r ...

Fixed navigation menu at the top of the screen

Can anyone help me with my navbar issue? I want it to stay on top of the page, but there's a huge gap between the top of the page and the nav bar. I've tried running a JS file, but it doesn't seem to fix the problem. Any ideas on how to make ...

Can you explain the purpose of CSS classes such as my-2, my-lg-0, and mr-sm-2 in Bootstrap 4?

I have searched through various questions and the Bootstrap documentation but haven't been able to determine the purpose of these classes on elements. Any assistance would be greatly appreciated! My goal is to adjust my search bar's size to 1/4th ...