Reputation: 459
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
Upvotes: 10
Views: 23984
Reputation: 53598
Edit due to CSS getting updated
Use scroll-margin-top
, introduced after the original answer was written.
Original 2018 answer
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);
}
Upvotes: 12
Reputation: 5673
You can also add a negative margin-top and the same amount of padding-top. For example:
.element {
margin-top:-20px;
padding-top:20px;
}
or even better
.element {
scroll-margin-top: 45px;
}
Upvotes: 2
Reputation: 39
If you are scrolling to a target from a non-fixed position on the page (say, from a sticky navigation bar) you have to take into account the current position that you're scrolling from. To do this, add window. scrollY to the y number in scrollTo (borrowing Mike's code):
function scrollToJustAbove(element, margin=20) {
let dims = element.getBoundingClientRect();
window.scrollTo(window.scrollX, dims.top - margin + window.scrollY);
}
Upvotes: 3
Reputation: 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);}
Upvotes: -3
Reputation: 75
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...!
Upvotes: -1