Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

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

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.

body{
position: relative;
-webkit-transition: left .2s ease;
}

Next thing I do is fire off a function when the page loads to replace all links with a function that will create the effect. I use some techniques I learned from a great article named From jQuery to JavaScript: A Reference to handle these operations without jQuery.

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.

body.style.left = "-100%";

There is an event listener that handles making it transparent while I move it to the other side of the screen.