Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does offset Bottom exist in vanilla js?

I found this sticky div snippet and altered it so that it appears stuck to the bottom of the window when the div hits the top of the page. I'm just curious is there a method of sorts for offset bottom. Here is the code :-

let Sticky = (function() {
    'use strict';

    let CSS_CLASS_ACTIVE = 'is-fixed';


    let Sticky = {
        element: null,
        position: 0,
        addEvents: function() {
            window.addEventListener('scroll', this.onScroll.bind(this));
        },
        init: function(element) {
            this.element = element;
            this.addEvents();
            this.position = element.offsetTop ;
            this.onScroll();
        },
        aboveScroll: function() {
            return this.position < window.scrollY;
        },
        onScroll: function(event) {
            if (this.aboveScroll()) {
                this.setFixed();
            } else {
                this.setStatic();
            }
        },
        setFixed: function() {
            this.element.classList.add(CSS_CLASS_ACTIVE);
        },
        setStatic: function() {
            this.element.classList.remove(CSS_CLASS_ACTIVE);
        }
    };

    return Sticky;

})();


//  Init Sticky
let sticky = document.querySelector('.sticky');
if (sticky) {
    Sticky.init(sticky);
}
like image 494
Umar Avatar asked Sep 09 '26 01:09

Umar


1 Answers

There's no offsetBottom on an element. Top and left are what are used to calculate the offset. If you want a lot more information you could use getBoundingClientRect. It returns information about the position of the element relative to the viewport. You get an object that looks like this:

{
  bottom: 775,
  height: 775,
  left: 0,
  right: 1322,
  top: 0,
  width: 1322
}

You call it like this:

var firstDiv = document.getElementsByTagName('div')[0]
var rect = firstDiv.getBoundingClientRect() 
like image 76
shadymoses Avatar answered Sep 11 '26 14:09

shadymoses



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!