SOLVED: onClick, Link to another page, then run page code

I’m trying to make a menu button go to another page, then scrollTo an anchor on that page, and then expand an element from within the Site code.

Doesn’t seem to work. The location.to () works, but it does not finish w/ the scrollTo(), and expand()…

Any suggestions?

import wixLocation from 'wix-location'

export function button_click(event) {
    wixLocation.to("/page2")
        .then(() => {
            $w("#anchor1").scrollTo();
            $w("#strip1").expand();
        })
}

Hello Arthur,

Two ways to acheive this.

  1. Either add a cookie or storage Item ,on button click, in the browser and do a normal wixLocation.to() when you go to that page read the cookie and if it matches, then scroll to the anchor.

  2. Add this code to the site code (A bit worse of a solution then the first)

Hope this helps,

Majd

Arthur:

wix-location.to() function does not return a Promise. The reason is that when it executes you are loading a new page. The suggestion from Majd is one approach which requires using cookies.

Another approach is to use a URL query.

Basically when you execute the wix-location.to() function you add a query that signals what you are trying to do.

Let’s say your page2 has several Anchors that you can scroll to and your page2 knows it will need to expand the related strip. What you can do is something like this.

// page is the URL for the target page i.e. "/page2"
// anchorNumber is a number within the range of anchors on the 
// target page
function loadPageAndScrollToAnchor(page, anchorNumber) {
    if (page && anchorNumber >= minAnchor && anchorNumber <= maxAnchor) {
        // Arguments are valid
        let pageQuery = '?anchor='+anchorNumber.toString();
        let targetURL = page+pageQuery;
        console.log('Loading page with URL: '+targetURL);
        wixLocation.to(targetURL);
}

Then in the target page (i.e. ‘/page2’) you add code to the $w.onReady() function that reads the query parameter using wix-location.query and then execute code on the target page using the query.

$w.onReady(() => {
    if (wixLocation.query.length > 0) {
        let anchorIndex = wixLocation.query.indexOf('anchor');
        if (anchorIndex != -1) {
            let anchorNumber = wixLocation.query[anchorIndex];
            let anchorElement = $w('#anchor'+anchorNumber);
            let stripElement = $w('#strip'+anchorNumber);
            anchorElement.scrollTo();
            stripElement.expand();
        }   
    }
});

Hope this helps
Steve