ScrollTo with Frozen Header

Whenever I set a scrollTo(), it works as if there was no header on my page. So, if my header is 20px in height, then I scrollTo an anchor, the page looks as if it scrolled 20px too far. Essentially, the code is not accounting for the header.

Is this intended, is there a work around?

Hi David,
Just as a thought, why don’t you set the anchor 20px before the actual point where you want to scroll to? I think that should fix it up quickly.

In certain instances that definitely would work. However, on a lot of my pages I have collapsible elements. So, depending on which elements are expanded or collapsed the anchors stay static but the elements move dynamically with collapsing.

You could set if Functions in order to achieve this, however, it might be a little to complicated to be practical. I guess there has to be an easier work-around.

Same issue.
If you set anchors, they don’t allow for collapsed items.
If you do it using scrollTo() you don’t need anchors, as you are specifying a $w page element.
I tried importing wix-window so I could use scrollBy(0,120) to offset my 120px header. I get JSON parse errors atm.

import wixWindow from ‘wix-window’;
export function buttonFoo_click(event, $w) {
$w(‘#foo’).scrollTo();
wixWindow.scrollBy(0, 70);
}
I also tried putting the scrollBy line inside a then() (as a callback fn) - but to no avail.

checked the console - wixWindow is a valid object.
For e.g. I can do this to allow for differences between my desktop and mobile header heights:

if (wixWindow.formFactor === ‘Desktop’) {
console.log(‘Yay this appears - it’s a desktop’);
wixWindow.scrollBy(0,120); // nothing happens here. why?
}
else {
console.log(‘it’s a mobile’);
wixWindow.scrollBy(0,70);
}

Well it turns out that scrollBy() is not a command to ‘scroll by’ an amount. It’s a listener that returns a promise - in other words - when scrolled by this amount, do this. No good for this purpose.

What I need is an offset adjustment for scrollTo()

The answer is obvious to me now. I just created an invisible (transparent) box on the page which was exactly the height of the header, gave it a name ‘wibble’ and then just used w$(‘#wibble’).scrollTo();
Bingo. It’s a bit of a hack, but it works for now anyway.

Feature request! - scrollTo accept X Y offset arguments in pixels. e.g. $w(‘#wibble’).scrollTo(0,120); would scroll to the element wibble, +120 px beyond (down)

UPDATE: This works best if the element is hidden on load, rather than transparent. That way you can see them easily when in the site editor, and they are not in the live page (although scrolling to them still works!)

1 Like