Skip to content Skip to sidebar Skip to footer

Div Position Based On Scroll Position

I would like my logo to scroll up and down vertically based on the scroll position on the website. In exactly the same way a default scroll bar indicates your position on the site,

Solution 1:

You could give something like this a try.

window.addEventListener('scroll', e => {
  const logo = document.querySelector('.scroll-text');
  const logoHeight = logo.clientHeight;
  const viewHeight = window.innerHeight;
  const maxLogoOffset = viewHeight - logoHeight;
  const scrollFraction = getElementScrollFraction(document.querySelector('body'));
  logo.style.top = maxLogoOffset*scrollFraction;
});

functiongetElementScrollFraction(elem){
  return elem.scrollTop / (elem.scrollHeight - elem.clientHeight);
}

You'll also need to add position:fixed; to the .scroll-text css.

Here is a working example: https://jsbin.com/yuholihece/edit?html,css,js,console,output

Solution 2:

Here is my solution.

Edited:

const docHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
const logo = document.querySelector('.scroll-text');
const logoHeight = logo.offsetHeight;
// to get the pseudoelement's '#page::before' top we use getComputedStyle methodconst barTopMargin = parseInt(getComputedStyle(document.querySelector('#page'), '::before').top);

let viewportHeight, barHeight, maxScrollDist, currentScrollPos, scrollFraction;

logo.style.top = barTopMargin + 'px';

window.addEventListener('load', update);
window.addEventListener('resize', setSizes);
document.addEventListener('scroll', update);

setSizes();


functionupdate() {
    currentScrollPos = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
    scrollFraction = currentScrollPos / (docHeight - viewportHeight);

    logo.style.top = barTopMargin + (scrollFraction * maxScrollDist) + 'px';
}

functionsetSizes() {
    viewportHeight = window.innerHeight;
    // to get the pseudoelement's '#page::before' height we use getComputedStyle method
    barHeight = parseInt(getComputedStyle(document.querySelector('#page'), '::before').height); 
    maxScrollDist = barHeight - logoHeight;
    update();
}

And if I understand correctly, you want #page::before element to have like margins on its top, left, bottom and right. If so, then I think it would be better to use this styling rules:

#page::before {
    content: "";
    position: fixed;
    top: 30px;
    bottom: 30px;
    left: 30px;
    right: 30px;
    ...
}

When you use position: fixed property (or position: absolute), you can stretch the element's width and height as you want by just setting top - bottom and left - right properties at the same time. P. S.: And also there is no sense in using display: inline-block, because position: fixed (and position: absolute) automatically sets display to block :)

Hopefully, this helps you!

Post a Comment for "Div Position Based On Scroll Position"