1

When clicking on a link smoothstate loads the new page's content, I'd like to identify the referring page with a class visible on the new page. Is there any way to do this?

PaulC
  • 185
  • 1
  • 1
  • 8

1 Answers1

0

This isn't the most dynamic solution, but what I ended up doing was setting classes to the anchor tags on the referring page. SmoothState has the onBefore() callback, which passes $currentTarget, i.e. the anchor element you clicked to start the transition. You could just as easily read the href off the anchor element and detect what you want to do that way as well (or store it off somewhere until later).

So in my HTML, I could declare a link like so:

<a href="new_page.html" class="special_case">New Page</a>

Then when I'm setting up smoothState, I declare my onBefore() callback:

onBefore: function( $currentTarget, $container ) {
  if ( $currentTarget.is( ".special_case" ) ) {
    // Some logic here
    globalSpecialCase = true;
  }
}

Since smoothState actually keeps you in the same place and just does an Ajax call to request new page HTML, then swaps out the page content, your current Javascript environment remains, global variables and all. So I set up a global flag (or you could make whatever data structure you want), and for that case with the special link, set the flag.

At the new page load, smoothState runs onReady(), that signals it's got the new page content and is ready to replace it and run the intro animations. You could check your flag here to do things before the page starts rendering, or you could wait until the onAfter() callback happens, which means the page is fully loaded and all the transition animations have run. At this point, I check the flag, run some logic, and unset it to make sure I'm ready for a new link click later.

onReady: {
  duration: 0,
  render: function( $container, $newContent ) {
    if ( globalSpecialCase ) {
      // Logic because this page was loaded from a special link
      globalSpecialCase = false;
    }

    // Inject the new content
    $container.html( $newContent );
  }
}

One thing to note: pretty much all the smoothState examples have the onReady duration set to 0, which means the onAfter() callback will happen immediately following onReady(), regardless of how long your animations take. If you actually want onAfter() to wait until the animations are done, make sure to set duration to the milliseconds your animations take.

Joel
  • 66
  • 2