javascriptjquerycsszeptowechat

emulating app-like swipe to switch pages on mobile website


I recently got curious about an interesting behavior of one of frontend frameworks out there for WeChat (威信).

If you look at https://weui.io/ using Chrome's Device Toolbar toggled on, and then select an element inside the list on the very first page - you will notice that it takes you to new page without any page reloads + the new page kind of slides-in from right to left.

But the most interesting part is that if you press BACK button (the usual "back" button top-left side of Chrome browser window), it will take you back to the first page. Also, if you open same weui.io with mobile, you will be able to choose certain item of the list, it will again load new page with this nice slide effect and then you just swipe left-to-right to return to previous page. So swipe works completely like inside an APP which I find very interesting!

I want to build same behavior on my site, but cant effectively emulate it.

My thoughts are I just load both pages instantly, second hidden, then I scroll this second page in or out as needed, but the point is I need to use this site-wide and such approach is quite clumsy for site-wide use. Alternatively, I can load second page with AJAX, but it still will not give me that swiping effect on mobile.

I have been inspecting the code but still cant fetch code parts covering that particular function.

Anybody been doing something similar to share exp? Thanks for any thoughts!


Solution

  • Turned out to be straightforward: it's all about History API (pushstate + popstate - there's also a good CSS-Tricks example to start off).

    Anyways, the History API is what helps you emulate a back/forward button's behavior even when you just do.

    $('.some_div').hide() $('.some_other_div').show();

    I found this post to be really useful - works almost out-of-the-box.

    Finally, History API Browser support can be found here.

    Would be happy to comment if any questions ;)