I’m working on a little demo mobile application for an upcoming project, and I wanted to add sliding transitions between pages. Pretty simple, right? You just use jQuery, jQuery Mobile, zepto, or one of a bunch of other frameworks, and they handle this for you. I didn’t want to. Part of my goal with this particular project is to challenge myself to work without a framework so that I can see how this stuff works by hand. Also I wanted to keep the HTML as slim and uncrufted as possible
Googling found very little to go on – except a micro solution for page transitions by FASW. I like it, but it’s still using someone else’s work, and I didn’t like adding even the little bit of HTML cruft that it needed.
So I rolled my own.
The solution I came up with actually is pretty lightweight and is powered by a little AJAX, some CSS transitions, and CSS transition events. It’s also important to note that this only works with WebKit. (My personal use case is for a mobile application with PhoneGap targeting Android and iOS, so I only need WebKit compatibility.)
First thing is to set the CSS of the body to have a transition on it, so when I move it around it’s animated.
Next step is to use AJAX to get the linked page.
Now comes the transitions. What I need to do to accomplish this page slide is:
- Slide the page off the screen to the left.
- Instantaneously move the page to the right side off screen
- Replace the contents of the body with the new content
- Slide the page on to the screen from the right.
I have to do it in that order. If you replace the contents independent of the animation, you get weird effects like the page changing then the animation happening, which looks jarring. Or you get the opposite, the transition happening, then the contents changing. Looks ugly. Trying to time these proved problematic. The best thing to do would be to wait for the transition offscreen to happen, then change the content, then move it back on screen. I was able to do this by using a transition event.
Basically as far as I can tell there is only one transition event “transitionEnd” regardless of browser manufacturer. I haven’t been able to figure that out. Animation events appear similarly limited. So here’s how I did it:
I moved the body to the left side of the screen.
There is an event listener that handles making it transparent while I move it to the other side of the screen.
I then replace the content, make it visible again, adjust the browser history, and move it back to the center.
Then to be thorough, I make sure that I reverse the process if the user hits the back button.
Is this the best way to do this? I have no idea. But it works for me and I couldn’t find a comparable solution via Google.
There is a demo here.(WebKit browsers only)
Full source code is available via github.