Search code examples
jqueryscrollsticky

Update an offset value in another function on resize


ive set up a simple example of an element that sticks to the top when you scroll past from it. https://jsfiddle.net/k9yadr8k/6/

But, if i would resize the window smaller then the content would push the element further away from the top of the window and that would make the sticky element snap into fixed position earlier. So my question is, how would i update the value of offVal on window resize inside stickIt function? Thanks

var offVal = $('#klots').offset().top;

function stickIt() {
  var scrTop = $(window).scrollTop();

  if (scrTop > offVal) {
    $('#klots').addClass('sticky');
  } else {
    $('#klots').removeClass('sticky');
  }
}

$(window).scroll(stickIt)

Solution

  • Essentially this:

    var $window = $(window)
    var $klots = $('#klots')
    var offVal = $klots.offset().top;
    
    // listen to resize event
    $window.resize(function () {
      offVal = $klots.offset().top
    });
    
    function stickIt() {
      var scrTop = $window.scrollTop();
    
      if (scrTop > offVal) {
        $klots.addClass('sticky');
      } else {
        $klots.removeClass('sticky');
      }
    }
    
    $window.scroll(stickIt)