I am currently dealing with some JavaScript code that scrolls to a specific div when clicked. However, I have encountered an issue where the div is displayed at the very top of the page, causing it to go behind a fixed header that is 90px in height. As a result, the title of the div is hidden.
To solve this problem, I would like to modify the code so that the div does not scroll all the way to the top, but instead leaves a certain height gap, for example, 90px. You can see the issue in the screenshot provided: https://i.sstatic.net/kDIAz.png
Here is the current JavaScript code:
this.scrollTo = function(eID) {
// The scrolling function
// was sourced from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
function currentYPosition() {
// For Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// For Internet Explorer 6 in standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// For Internet Explorer 6, 7, and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
};