1

There is a div, style fixed 60px from top. I want when I scroll down and the distance of div from top reached 10px, the div stop there for the rest of scrolling also when I scroll up it goes back to the old style 60px from top. I did a lot of search but I did not found anything like this. But there is a code which calculate distance from top:

var scrollTop     = $(window).scrollTop(),
    elementOffset = $('#my-element').offset().top,
    distance      = (elementOffset - scrollTop);
Phil Tune
  • 3,154
  • 3
  • 24
  • 46
mhndlsz
  • 106
  • 1
  • 8
  • possible duplicate of [Sticky header CSS / JS](http://stackoverflow.com/questions/6913086/sticky-header-css-js) – Alan H. Nov 18 '14 at 20:46

2 Answers2

0

Here's one way to do it using pure javascript. You can replace some of the selectors like document.getElementById with jQuery selectors like $("id") if you like.

window.onscroll = function(){
  var el = document.getElementById('sticky'),
      s = window.pageYOffset || document.documentElement.scrollTop, // how much page is scrolled
      t = document.getElementById('main').getBoundingClientRect().top; // top of main div
  
  if(s > t){
    el.style.position = 'fixed'; //make position fixed instead of absolute
  }else{
    el.style.position = ''; //clear styles if back to original position
  }
}
body { 
  min-height: 200em; 
  margin: 0;
  padding: 0;
}

header {
  background: black;
  color: white;
  padding: .5em;
}

#main { position: relative; } /* important so the sticky box positions relative to this */

#sticky {
    background: cornflowerblue;
    padding: .5em;
    position: absolute;
    right: 1em;
    top: 1em;
    width: 10em;
    color: white;
}
<header>This is just a page header or toolbar.</header>

<section id="main">
  <div id="sticky">This should stick to the top when scrolled.</div>
</section>
Barry T. Smith
  • 1,021
  • 7
  • 10
0

Here's a jQuery solution. If we're more than 10px from the top of the page add a is-sticky class to the element which you can then style with CSS.

// store the element in a variable
var element = $('.item'),
    visible = false;

// on scroll
$(window).scroll(function() {

  /**
   * store the scroll distance in px
   * from the top of the viewport
   */
  var scroll = $(window).scrollTop();

  /**
   * if the scroll is greater than or equal
   * to 10px add a class of .is-sticky to the element
   * otherwise we're less than 10px from the top
   * of the document and therefore don't want
   * the element to have the .is-sticky class
   */
  if(scroll >= 10) {
    if(!visible) {
      element.addClass('is-sticky');
      visible = true;
    }
  } else {
    if(visible) {
      element.removeClass('is-sticky');
      visible = false;
    }
  }
});
Oliver
  • 77
  • 1
  • 8