4

let's say I have the follwing function:

window.smoothScroll = function(target) {
  var scrollContainer = target;
  scrollContainer.scrollIntoView(true);
}

How can I make the page scroll 20px above the element instead of scrolling to the element itself?

Thank you

itailitai
  • 337
  • 3
  • 14

3 Answers3

8

Get the dimensional information for your element and then rather than scrolling it into view, tell the window to scroll to your element's top minus 20:

function scrollToJustAbove(element, margin=20) {
  let dims = element.getBoundingClientRect();
  window.scrollTo(window.scrollX, dims.top - margin);
}
Mike 'Pomax' Kamermans
  • 44,582
  • 14
  • 95
  • 135
  • 1
    Thank you, this seems to work. but instead of the getBoundingClientRect() I used .offsetTop which seemed to work fine. – itailitai Sep 29 '18 at 16:50
  • 3
    It only _seems_ to work fine, but the offsetX/Y properties are _relative_ values, measured with respect to the parent's bounds. If your intention is reliable scroll, based on where the element _actually is_, then don't make that change, and stick with `getBoundingClientRect` =) – Mike 'Pomax' Kamermans Sep 29 '18 at 18:13
  • 1
    There's a more fully fleshed out answer/demo for this at https://stackoverflow.com/questions/49820013/javascript-scrollintoview-smooth-scroll-and-offset – tarskiandhutch Jul 02 '20 at 20:55
0

Well, for smooth scroll you can use jQuery animate(). Check the code below:

window.smoothScroll = function(target, above, speed) {
  let $scrollContainer = $target;
  jQuery('html, body').animate({
    scrollTop: jQuery(scrollContainer).offset().top - above
  }, speed);
}

[Note: above will be your 20 (as you wanted 20px above the target), speed will be any number say: 900 like that.]

If it helps...!

rony2k6
  • 77
  • 5
-1

Please change variables definations. $scrollContainer and target vars are not same, you can use at below

window.smoothScroll = function(target, above, speed) {
    let scrollContainer = target;
    $('html, body').animate({
        scrollTop: jQuery(scrollContainer).offset().top - above
    }, speed);}