kosmosan
kosmosan

Reputation: 373

Scroll to element's offset depending on header height

I've a header that changes its height depending on the window scroll:

$(window).scroll(function() {
    var $header = $('header');
    if ($(this).scrollTop() > 250) {
        if (!$header.hasClass('sticky')) $header.addClass("sticky");
    } else {
        if ($header.hasClass('sticky')) $header.removeClass("sticky");
    }
});

The sticky class just changes the height of the header and other styles. The issue is that I need to animate the body to the section by clicking on a header item menu:

$('a.smoothScroll').on('click', function(e) {
    e.preventDefault();
    var $target = $($(this).attr('href'));
    var $header = $('header');
    $('html, body').animate({
        scrollTop: $target.offset().top - $header.height() + 'px'
    }, 300);
});

So, once the page is loaded, if I click on an menu item, $header has a height value, but once the scroll reaches 251 pixels, its value changes and I don't know how to inform the animate function.

I'm stuck at this point, how can I animate the page scrolling to the appropriate value?

Upvotes: 3

Views: 6000

Answers (1)

UltrasoundJelly
UltrasoundJelly

Reputation: 1900

All you need to do is add back the height of the shortened header.

$(window).scroll(function() {
  var $header = $('.header');
  if ($(this).scrollTop() > 100) {
    if (!$header.hasClass('sticky')) $header.addClass("sticky");
  } else {
    if ($header.hasClass('sticky')) $header.removeClass("sticky");
  }
});
$('.smoothScroll').on('click', function(e) {
  e.preventDefault();
  var $target = $($(this).attr('data'));
  var $header = $('.header');
  $('html, body').animate({
    scrollTop: $target.offset().top - $header.height() + 50 + 'px'
  }, 300);
});
.header {
  height: 200px;
  background-color: grey;
}

.sticky {
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=header>HEADER!</div>
<button class=smoothScroll data="#1">clickMe
</button>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id=1>Scroll to Me</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>

Upvotes: 2

Related Questions