Is there a way to determine if a div is positioned 100px from the bottom edge?

When using the sticky class to stick a div, I encountered an issue where it sticks correctly from the top but overlaps the footer at the bottom.

https://i.sstatic.net/28A3A.jpg

Here is the HTML code:

<div class="tab-content">
    <div role="tabpanel" class="tab-pane active " id="menu1">
    <div class="col-sm-12"><div class="clear">&nbsp;</div></div>

    <!-- LEFT NAV START -->
    <div class="col-sm-3" id="sticky-anchor2">
    <div class="sticky2">
    <span style="color:red"><strong>Menu Group</strong></span>
    <ul aria-labelledby="dropdownMenu1">
    <?php foreach ($categories as $key => $value) { ?>
        <li role="presentation">
        <a role="menuitem" tabindex="-1" href="<?php echo $nav_url; ?>#cat_<?php echo str_replace(' ', '_', trim($key)); ?>" class="anchorLink" style="color:#FFF !important;">
        <button class="btn btn-danger btn-sm btn-block setlbl" type="button"><?php echo $key; ?></button></a>
        </li>

        <?php } ?>
        </ul>
</div>

This is the jQuery code I am using:

var window_top = $(window).scrollTop();
var div_top2 = $('#sticky-anchor2').offset().top - 100;
if (window_top > div_top2) {
    $('.sticky2').addClass('sticky stick');
} else {
    $('.sticky2').removeClass('sticky stick');
}

I would like the div to remove the stick class when it is about 150px from the bottom. How can I achieve this?

Answer №1

Check out this solution:

Give it a try by visiting my fiddle: https://jsfiddle.net/v3kq1ddd/ or expand the snippet to full screen and adjust the window size to witness the border color transition from red to blue.

$(document).ready(function() {
    $(window).resize(function() {
        var eHeight = $(".sticky2").height();
        var eTop = $(".sticky2").offset().top;
        var tot = eHeight + eTop;
        var heightDifference = $(window).height() - tot;

        $('.height').text(heightDifference);

        if(heightDifference < 150) {
            $('.sticky2').addClass('blue');
        } else {
            $('.sticky2').removeClass('blue');
        }
    });
});
.sticky2 {
    height: 200px;
    width: 200px;
    border: 1px solid red;
}

.blue {
    height: 200px;
    width: 200px;
    border: 1px solid blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<lable>Space to bottom</lable>
<div class="height"></div>
<div class="sticky2">This is a div</div>

Answer №2

When calculating the height of a document and window, it's important to consider any specific div that may need to be included.

For accurate scroll calculations, the 'Scroll' event should be utilized to track scroll amounts continuously. Additionally, when dealing with a 'sticky stick', remember to use a hyphen between the classes, not two separate classes.

$(window).scroll(function(){ 
           var scrollamount=$(window).scrollTop();
            var totalheight=($(document).height() - ($(window).height()));

             if(scrollamount > totalheight-100)
                {
                  $('.sticky2').addClass('sticky_stick');
                 }
             else
              $('.sticky2').removeClass('sticky_stick');



 });

JsFiddle: https://jsfiddle.net/2jo69opo/

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

Various settings in JQuery UI Slider

Does anyone know how to customize the steps in a jQuery UI slider? I want to set specific values as steps, like 0, 1200, 2000, 2200, and 3000. Any suggestions on how to achieve this? const rangeSliderInit = () => { const valueArray = [0, 400, 1000, 1 ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

A guide on instantly updating displayed flat/section list elements in React Native

I am in the process of creating a screen called ContactListScreen. The direct child of ContactListScreen is ContactItems, which is a sectionList responsible for rendering each individual ContactItem. However, I have encountered a problem where my ContactIt ...

I'm having an issue with my Bootstrap tabs - they seem to be unresponsive when clicked

I've been working on a Bootstrap website and have run into some issues that I can't seem to resolve. One problem I encountered was with a set of tabs that were supposed to be interactive, but for some reason, they weren't working as expected ...

Vue - Utilizing mapState in Vuex to display the contents of the first object within an array

I am trying to display the names array from the first object in players using mapState with Vuex. Currently, the objects in players are listed based on their titles, but I want to filter them based only on the names in the first object for the current page ...

Is there a solution for the noticeable delay in loading fonts on a web page?

I've encountered an issue in my React project where a Google font I'm using seems to briefly load as a different font before switching to the correct one. How can I prevent this from happening? This is how I'm loading the font in public/ind ...

Only output to the console if the data returned from an AJAX request has been

Here is a script that I created: <script type="text/javascript> $('.storage').html(""); setInterval(function(){ $.get('./playcommand.php', function(data) { if($('.storage').html() !== data){ ...

Trouble with the Width of Selection Box Options

Encountering a peculiar issue with multiple select boxes in my project. Some of the options within the select box are exceeding the width of the box. Proper Dropdown View: https://i.sstatic.net/xDy6I.jpg Incorrect Dropdown Display: https://i.sstatic.ne ...

Tips for choosing a week on a calendar with JavaScript

Here is the code for my calendar: <script> $(document).ready(function() { var events = <?php echo json_encode($data) ?>; $('#calendar').fullCalendar({ header: { left: 'prev,next', center: &apos ...

Expect a reply within the loop

One of my endpoints takes some time to generate data, and I have another endpoint to retrieve that generated data. I make the initial call using await, extract the ID from the response, and then keep calling the second endpoint until the status is not "Suc ...

What is the best method to loop through this object with JavaScript?

Suppose I have the following data: let testData = { 'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]], 'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]] }; What is the best approach to iterate through this data using Jav ...

Having issues with the onclick() function not functioning properly with Jquery?

Yesterday, I successfully integrated some Jquery code into my website. However, when I attempted to add more code today for a new feature, everything seemed to stop working. Even the code that was functioning perfectly yesterday has now ceased to work. The ...

Showcase text in a straight row by utilizing ng-repeat and bootstrap

My goal is to show each word on a new line, similar to how words are displayed in a hangman game. The words should be displayed as blanks. <body ng-init="models = [['H','a','p','p','y'],['X',& ...

jquery function context

I'm having trouble grasping function scope in this scenario. When a button is clicked, it triggers a dialog box with a textarea inside displaying a URL that can be copied for camera setup. <button id="axis-details" onclick="apikey('<?php e ...

Ensuring that the empty bubble remains undisturbed, here's a guide on effectively implementing the if

I need assistance with adding an "if condition" to my text field. The condition should prevent the empty bubble from appearing when the send button is clicked. function verifyInput(){ var currentText = document.getElementById("demo").innerHTML; var x ...

Having trouble transmitting information from the view to the controller in Asp.net MVC with Jquery

I've been struggling to send data from my View to the controller because it always shows a count of 0. The request carries the data according to the developer console, but the action method fails to receive it. I'm at a loss in identifying the pr ...

What is the best way to fetch HTML content using JavaScript?

I needed to incorporate JavaScript for fetching HTML code. I structured the HTML code in the following manner; <html> <div id="tesingCode"> <h1>Title</h1> <p>testOfCodetestOfCodetestOfCodetestOfCode</p> </div ...

Uploading an image via Chrome and transferring it to a server using PHP: a step-by-step guide

In my web application, I am looking to allow users to easily upload images to a server. My idea is for the user to simply paste the image into their Chrome browser (e.g. a print screen), then have the image stream posted to a PHP page where it will be conv ...

The div will not receive the JSON response

I am currently working with a <script> that includes functions for autocompletion and item selection: // autocomplet : this function will be executed every time we change the text function autocomplet() { var min_length = 0; // minimum character ...

Utilizing CSS to transform text with a sleek, animated writing effect

I have utilized CSS to create a captivating animation effect where text is written out in a smooth style. I am seeking assistance in replacing the current text with a different one while maintaining the same effect. HTML & CSS .typed-out{ overflow: ...