KYSSE
KYSSE

Reputation: 385

Make div stick to the bottom of the page when full height of div is reached on scrolling down

I have a container on the left hosting a div with a fixed height of 1000px. I than have a container on the right hosting general mock content so the page scrolls.

As you scroll down the page you will notice the div on the left side has an image. When the image ends and you see gray; you have reached the full height of the container. (1000px).

I want to make it so when you scroll the entire height of the div (1000px). The container than becomes fixed to the bottom of the viewport. Making it so its bottom half remains in view instead of scrolling passed it. Essentially no gray on the left should ever be shown.

I hope that makes sense. I drew up a fiddle to make things easier.

JS FIDDLE

Upvotes: 0

Views: 867

Answers (2)

Joey Breithaupt
Joey Breithaupt

Reputation: 95

I'm not sure if you need it in jquery for any reason, but I rewrote it in Vanilla JS. It also calculates the div height for you. So resizing the window or the div should give you the same effect.

document.addEventListener('scroll', () => {
  let img = document.querySelector('.mgc-img')
  let scrollPos = window.scrollY
  let x = img.clientHeight-window.innerHeight

  if(scrollPos > x) {
    img.classList.add('make-fixed')
  } else if(scrollPos < x) {
    img.classList.remove('make-fixed')
  }
})

Updated fiddle. If you need it in jquery and want it to calculate the div height for you, you can use @EderChrono code, just change the startFixedHeight variable to this:

var startFixedHeight = image.height() - window.innerHeight;

Edit: This also requires the class change that @EderChrono suggested.

Upvotes: 1

Eder D&#237;az
Eder D&#237;az

Reputation: 2071

First your .make-fixed class should contain a bottom rule like this:

.make-fixed {
    position:fixed;
    bottom: 0;
}

After that in your JS code you should stop toggling classes because that's what makes the flickering happen:

$(window).on('scroll', function () {
    var scrollTop = $(window).scrollTop();
    var image = $('.mgc-img')
    var startFixedHeight = 1000 - window.innerHeight;
    if (scrollTop > startFixedHeight && !image.hasClass('make-fixed')) {
        image.addClass( "make-fixed");
        image.removeClass( "make-absolute" );       
    }
    if (scrollTop <= startFixedHeight && !image.hasClass('make-absolute')) {
        image.removeClass( "make-fixed");
        image.addClass( "make-absolute" );   
    }
}); 

Updated fiddle https://jsfiddle.net/ckud4xLv/5/

Upvotes: 0

Related Questions