0

I need to create a bootstrap 4 layout with an image that sticks to top after the page is scrolled and the image reaches bottom of the header, but after the page is scrolled down to the footer and footer enters viewport the image should start scrolling again with the page. The image should be sticky only on large and extra large bootstrap 4 grids. The behavior I'm looking for should be the same as if the new bootstrap 4 class "sticky-top" was added to the image, only with css and jquery because I can't use sticky-top class due to the lack of browser support. Is there a way to do this with jquery?

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
   <header>header sticks to top</header>
    <div>breadcrumbs that scroll along with the page go here</div>
    <div class="row">
   <div class="col-12 col-lg-6">
        <img src="image.jpg" class="img-fluid" alt="image">
      </div>
      <div class="col-12 col-lg-6">
       <p>Bunch of random text goes here</p>
      </div>
 </div>
    <footer>Footer stuff goes here</footer>
 
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
Goran Tesic
  • 719
  • 1
  • 13
  • 28
  • 1
    Can you show what you have tried by making a demo at codepen or jsfiddle or any third party service, it will be easy for us to understand the problem.. – Niraj Feb 14 '17 at 14:33
  • I would like to create something like they have on apple.com on this page for example: http://www.apple.com/shop/buy-mac/macbook-pro?product=MLH42LL/A&step=config# – Goran Tesic Feb 14 '17 at 15:08

1 Answers1

0

A cool library has been created to detect which viewport is currently being used here: https://stackoverflow.com/a/22885503/7053420

Then you could do something like so:

function checkOffset() {
if($('.img-fluid').offset().top + $('.img-fluid').height() 
                                       >= $('#footer').offset().top - 10)
    $('.img-fluid').css('position', 'absolute');
if($(document).scrollTop() + window.innerHeight < $('#footer').offset().top)
    $('.img-fluid').css('position', 'fixed'); // restore when you scroll up
}

But only execute the below, depending on viewport detected.

$(document).scroll(function() {
checkOffset();
});

Once you hit within 10px of the footer the image will stop scrolling with the page. When you scroll back up the function then re-instates the image in it's place.

Community
  • 1
  • 1
Tristan Hudson
  • 151
  • 1
  • 12