Bookboard – A Model for the Future of the Web

One of the missions of PhoneGap has always been to bring about its own demise. The PhoneGap team wants the web to have all the functionality that we currently enjoy on devices so that there isn’t a need for PhoneGap to exist. It’s one of the reasons I love the project; I think that’s the perfect goal. I hope we get away from app stores and back to a world where the web rules all. There are obviously many things that have to happen before that becomes a reality but every once in a while I see a glimpse of what the web could be if that vision comes to pass. The latest iteration of that is Bookboard. (Sign up here)

Book Board Selection Screen

Bookboard is a web app that was written for the iPad. It makes heavy use of iOS specific features that allow websites to add themselves to the home screen for a full-screen experience and provide specific icons so that to the end user, it kind of feels like an app that just didn’t come from the app store. Even though it’s iOS-specific right now, the UI design is such that it would work across platforms. So many apps, even PhoneGap apps, follow the specific list->detail form that brings a lot of baggage with it. You have to work at making sure your list/detail view works the way it’s supposed to on iOS or Android (or other platforms). But Bookboard has a very design-heavy UI that lends itself to any platform. The books intuitively ask to be swiped from side to side as you are looking through them (with a nice parallax effect in the background) and when you go into the book itself you use the same swipe motions you would expect. It’s list-detail but brought to life in an interactive way.

Reading a Bookboard Book

Bookboard also makes use of hardware acceleration of CSS for many of its transitions. Everything on my iPad 2 is incredibly fluid and it’s difficult to tell that it’s *not* native. One of the things many app developers have to deal with is making their content feel native without it actually being native. The Bookboard approach seems ideal to me. They’re using a UI that hasn’t been replicated by every other app so they get a bit of leeway in terms of performance, but they don’t need it because they’re offloading to the device hardware via CSS. It works out very well.

Bookboard Menu Screen

Beyond the tech side Bookboard is simply a beautiful, well-designed app. It’s meant for children to read (and they can unlock achievements for reading more books) so it has to be intuitive, but it also looks great. Attention to detail like the parallax scrolling add a friendly touch and my daughter loved the app. She knows how to use an iPad and scrollable books, friendly gestures, and words that are magnified on touch all came naturally to her. If you’re a parent with a kid who enjoys reading (or you want them to enjoy it more) Bookboard is well worth a try.

This is how I want the mobile web to look and behave. Bookboard leverages the mobile-app centric parts of iOS to create an app-like experience while still retaining the unique, design-centric approach that has made the web so great. It’s this kind of custom UI and design influence that starts to make developers stop and think about whether they go native or web. A basic list-centric app isn’t that tough to do in native so more often than not, it probably makes sense just to go native. But the kind of custom UI and design that Bookboard uses lets you involve the designers much more deeply in the process. Since most designers (should) feel comfortable with CSS, they can jump in and contribute directly to the end result. If you can get performance like this using web technologies, I think it becomes a tougher sell to try and do native when web gets you more platforms, more reach, more designer input, and more deployment flexibility.

Hopefully in the next couple of years apps will have been replaced by experiences like Bookboard. It would make my home screen a much more interesting and beautiful place while giving developers ultimate flexibility. That’s a big win for the web. I encourage you to go sign up and see what I mean.

Web versus Native Economics and User Adoption

Vibhu Norby has a detailed post on why his startup is pivoting from mobile first to web first. And ultimately it comes down to economics. This has been one of the big problems with the web versus native. In general, it’s been easier for developers to make money with native apps. That ease comes at a price; you’re locked in to a specific platform, and you’re at the mercy of the keepers of that platform. But all-in-all compared to the cheap, throw-ads-everywhere model that has driven the web economy for so long, it was a breath of fresh air. People were willing to give up 30% for access to a new, untapped, and profitable market.

That market still exists, but it isn’t quite the gold rush it used to be. What more people like Vibhu are realizing however, is that you don’t have to choose between throwing a hail-mary on an app store and cheapening your user experience with ads. You can focus on building a great web experience and adding value, charging for that value, and then using mobile as an added touch point to your service. And it turns out that the early process of getting and retaining users is quite a bit less painful on the web.

You have an entirely different onboarding story on the web. You can test easily, cheaply, and fast enough to make a difference on the web. You can fix a critical bug that crashes your app on load 15 minutes after discovery (See Circa). You can show 10 different landing pages and decide in real-time which one is working the best for a particular user. You can also close a viral loop: A user can click an email and immediately be using your app with you. You can’t put parameters on a download link and people don’t download apps from their computer to their phone. Without the barrier of a download + opening the app to try your product, you can prove value to the user immediately upon their first impression, as is with Google. In addition, the experience of signing up for a service is superior in every way. Typing is easier. Sign-up with OAuth is faster. Tab to the next field. Provide marketing alongside sign-up as encouragement. Auto-fill information is a feature in every browser. The open eco-system of the web and 20 years of innovation has solved many of the most difficult parts of onboarding. With mobile, that kind of innovation is lagging significantly behind because we create apps at the leisure of two companies, neither of which have a great incentive to help free app makers succeed.

As a personal example, I have a long Facebook password with lots of random characters. Nothing annoys me more than trying to sign up for anything with Facebook on a mobile app because my password is hard to type, it’s not saved, and I can’t use the key combination I’m familiar with on the desktop. That’s not a good user experience.

There is so much that’s inherently good about the web, as Christian Heilmann eloquently points out, that it’s a shame to think of it last or as a throwaway just because mobile is the new hotness. Since the web has gotten very good at supporting rapid testing and process for getting users on board why not leverage that and then use mobile as just another way for customers to access your web-centric content/services?

Longer term I continue to hope that the good practices from the web will bubble up on mobile devices. From both a core API/feature standpoint and from a user experience standpoint. Once that happens it will become a much easier sell to content creators and developers to go all in with the web and build great web experiences on mobile instead of building native apps that tie back to the web.

Using Ratchet with PhoneGap

When I saw the Ratchet project I was stoked. While the initial site talked about being able to prototype iPhone applications with HTML/JS/CSS it was pretty apparent that this could be something even bigger than that. And sure enough, on their README page it talks about long term goals:

We eventually want to extend Ratchet beyond the prototying for iPhone and create HTML/CSS/JS components for iPad and Android devices. Our dream is that Ratchet becomes the best way to create mobile experiences with web standard languages.

To me, that means this could be a great project for PhoneGap applications. So I threw it into a project and looked at getting it running. Unfortunately nothing happened. I could get some components to work but once I tried to move between pages it wouldn’t respond. I tracked it down to the push.js-esque functionality that they’re using. Specifically, it’s a single line of code that causes issues.

if (xhr.readyState == 4) xhr.status == 200 ? success(xhr, options) : failure(options.url);

The issue is that PhoneGap only seems to return a status of 0 when using XMLHttpRequest. I’m fairly sure this has something to do with the fact that it’s loading from the file system and not a server, but I’m not 100% sure. By making sure that Ratchet accounts for status of 0, page transitions work perfectly.

if (xhr.readyState == 4) xhr.status == 200 || (xhr.status == 0 && options.url.indexOf('file:///') != -1) ? success(xhr, options) : failure(options.url);

I’ve got the full project up on GitHub and you can bring it into PhoneGap Build and test it yourself. I’ve only tested it on iOS but it works pretty damn well. I’m definitely intrigued. I’ve also posted this to the Google Group to see if they can support this out of the box.

Update: Simon mentioned in the comments below that by tweaking the code to check for status 0 AND file system, it would be safer. So I modified the ratchet.js file in my project to take that into account. Thanks Simon.

The Mobile Web is Always the Right Answer

It’s been interesting to continue to watch the fallout of Facebook’s native announcement because so many smart people are discussing the web versus native dynamic. What I find both fascinating and odd (yet unsurprising) is that “HTML5″ continues to have vague and very subjective connotations. In the context of this debate, HTML5 seems to really mean hybrid applications that are built with technologies like Cordova/PhoneGap. And for proponents of native that’s a great way to frame the debate because when compared on equal ground, native will win most of the time. That’s because native apps were meant to be apps whereas PhoneGap/Cordova apps are really web content that’s built to behave in an application world. The suit will never fit quite as well as it does on Mr. Native.

But in some ways, that’s not the point. The real debate, and the most important one is the role of the web in the future of mobile devices. Currently there are number of techniques to bring the web to mobile devices. There’s responsive design, there’s the m-dot, there’s PhoneGap/Cordova, etc. They all have specific plusses and minuses depending on what you’re trying to accomplish. But they’re also all very rooted in the ethos of the web.

When people talk about HTML5 versus native it’s often going to be in the app context. And then the narrative can become “HTML5 isn’t ready”. That’s bullshit. HTML as a technology is more than ready to help you create apps and content for mobile devices. You may not get access to every device API and it may not fit into an app store, but the corollary is that you don’t need an app store. You can create whatever content you want and give it to the world. You have to make sure the experience is good on devices, but you don’t have to pass anyone’s arbitrary test to play the game, you don’t have to lock yourself into a specific platform. You just create your experience and let the world decide if it’s worth visiting. And users still do a ton of interacting with the web on their phone through a browser.

Facebook Mobile Usage Numbers

Facebook’s mobile usage numbers by platform

The image above, from PhoneGap Day EU during a talk by Facebook’s Simon Cross, perfectly illustrates that. There’s definitely a legitimate argument to be made that part of the reason the web usage is so high is because the hybrid Facebook apps were horrible to use. But look at the graph again. Mobile web usage is levels of magnitude above the native apps. That’s not just from a bad experience. That’s because people spend a lot of time in their browser on smartphones.

We’re in a fantastic time for the mobile web because there are so many options for creating mobile web content. But no matter how you want to show your content, it’s never a good idea to ignore the mobile web. Every great app I can think of has some tie to the web. Foursquare, Yelp, Untappd, and Twitter. The native app experience is a critical part- and it may even provide the best experience currently- but the web is even more vital to the long term survival of those companies. Never, ever discount HTML and the web. You’ll regret it. You can ask Path in a year how it feels.

Don’t Settle for a Mediocre HTML5 App Experience

Since Facebook announced their decision to ditch their HTML-centric app experience for a native one, I’ve been doing a lot of thinking about what that means for the HTML5 versus native debate. Unfortunately we’re at a point in the circle of tech where it’s easier to build a great native experience than it is to build a great HTML experience. I’d argue it’s not impossible to build a great HTML experience on mobile devices, just more difficult (I think Untappd is a great example, photo bugs not withstanding). The problem is that runs directly counter to why most people choose to go the HTML route and that causes a host of issues.

Today, when someone decides to build a mobile app from HTML, it’s primarily a developer-focused decision and not a user-focused decision. What I mean by that is that often times HTML makes it easier/faster/cheaper for someone to deploy a mobile app. Maybe they have a bunch of web developers and want to quickly crank out an app. Maybe they want to target multiple devices and they see HTML as a way to reuse code. Those aren’t bad reasons to chose HTML5 necessarily, but they do drastically change the goals of a project from “make this as awesome as possible” to “make this as good as we can with our constraints”.

So it’s no wonder that a lot of the HTML mobile app experiences are subpar. They started with the very premise of wanting to do it cheaper/faster/easier. That’s not a path to software greatness. Facebook again provides an example here. They had a ton of HTML content they wanted to reuse and an HTML-centric app was a fast, easy way to repurpose that content for mobile apps. Plus they could deploy it to lots of different kinds of devices with minimal code changes. They didn’t start from a place of wanting to make a great mobile experience, and the results spoke for themselves. When pressure finally got to a breaking point and they had to create a great mobile experience, they went with the clearest path to that route – native. This tweet by Josh Clark implies as much. It wasn’t that the HTML app was fundamentally unfixable, it was that (I assume) they looked at what it would take to make it as good as the native app and decided it wasn’t worth the effort.

I don’t blame people for making that judgement call. The PR boost that people used to get from throwing HTML5 into their marketing has started to subside and at the end of the day your users aren’t going to forgive a crappy mobile experience because you got 5 in a row on buzzword bingo.

HTML developers are in a rough spot right now because once you take out the faster/easier/cheaper argument, it’s tough to provide reasons why HTML is better than native apps. I see three main reasons. One, the web is a fantastic medium for designers and allows very unique experiences. Two, the ecosystem around web technologies has never been stronger and the number of cool frameworks, tools, and libraries that are available to web developers could have a significant impact on the kind of app you can build. Three, it never pays to bet against the web.

The first two I’ll cover in later posts and the third is the most subjective anyway so I want to talk briefly about that. For most apps, the future isn’t going to matter, so this isn’t a “future proof your code” argument. It speaks deeper than that. Do you want to be the kind of company who makes the future, or do you want to be the kind of company who follows along? HTML is the future. Just like native fell out of favor on the desktop, native is going to fall out of favor on mobile devices. The APIs are getting better for device access. Core graphical capabilities are being added that will make for nicer components, better experiences, and faster UIs. And the web is bigger than one company. The web is the great equalizer in tech. That leads to its own sets of drama about how we add features, but at the end of the day, no one will own or control the web. I see the web as a glacier. It tends to move very slowly, which can be a drawback. But when it moves, it brings everything with it and it carves a deep, permanent path that completely changes the landscape. That’s a tough thing to try and stop or stand in front of.

When you see an HTML mobile app that’s not as fast or snappy as it should be, think about what problem they were trying to solve. If the answer isn’t “build the best app possible” then don’t take that as a good example of what HTML is capable of. And if you’re building an HTML app put the same amount of effort, thought, and design into it as you would a native app. With the breadth of design possibilities, the HTML/JS/CSS ecosystem, and some forward-looking vision, you can build something that helps turn the conversation back to why the web is such an awesome medium for applications.

A Response to Benjamin Sandofsky’s Shell Apps

Dion Almaer retweeted an article by Benjamin Sandofsky that covers “shell apps”, or HTML/Hybrid apps in contrast to native apps. His thesis seems to be, from his post:

If you plan to write an app for iOS or Android, you will save time and create a better product if you stick to Objective-C and Java, respectively.

Which I agree with in principle, but I also found some of his arguments deeply flawed. He spends a lot of time talking about the cross-platform problem of trying to build a web-experience that looks native on iOS and native on Android. Specifically he calls out differences on iOS and Android:

The harder problems are inconsistencies in platform conventions. The iPhone uses Helvetica as its system font, while Android uses Roboto. iOS transitions between views by sliding new views in from the right, while Android uses a zoom effect.
You could recreate each platform in HTML5, but that requires a lot of work. You could design everything around an iOS look, and settle for things looking weird on Android. You could create a platform agnostic design language, making things equally weird for everyone. In a web view, it’s an uphill battle for consistency, whereas going native provides consistency for free.

Put aside the fact that if you’re doing native development you’re writing two different versions anyway (I’m not sure why that would be a knock against an HTML-centric solution), why do you have to design around an iOS or Android specific look?

The Native Component Question

I know it’s harder, and potentially more expensive, and requires more design sense, but why should developers of HTML-centric apps for mobile devices be locked into the specific UI look and feel of that platform? I’m not talking about UI paradigms (eg, soft back buttons on iOS, menu buttons on Android), but the specific look of apps. Instead of skinning your application to look like an iOS app and then try to make it look like an Android app, do a design that looks unique and polished that would translate well across both platforms. Then as you start to get into the specific differences (he brings up a good point about transitions) you can implement those device/platform-specific patterns. To me one of the beautiful things about the HTML/JS/CSS stack is the freedom with which we can develop. Bringing that to mobile applications, and letting some great CSS/HTML designers loose on that platform is a great thing. And it’s one of the reasons I love PhoneGap.

There are definitely some performance implications by going with a shell app/HTML-centric app approach. And as your application gets more complex, those will pop up more and more. So it’s something to be very aware of. Benjamin quotes some of the reasons he sees for people choosing HTML-centric apps: “we need to release faster”, “write once, run anywhere”, “HTML is easier”. I’m not sure any of those are great reasons to choose HTML-centric apps. Instead I see the primary benefits of the HTML approach as not being locked into a specific platform or deployment model. With HTML you can repurpose code for mobile web and you can target new platforms as they come (no device is not going to support HTML). But maybe most importantly, with HTML you can easily create custom app experiences. There are some great designers out there who can do amazing things with HTML and choosing something like PhoneGap lets you use those skills to create a unique web-like experience with all of the device features users expect from native apps.

Is it a silver bullet? Definitely not. But I think dismissing HTML-centric apps as being done because they’re cheaper/faster/easier doesn’t do them justice. For some kinds of apps, the HTML-centric approach is just better. There’s an amazing community of people that know HTML/JS/CSS, the web is the ultimate platform for reach and flexibility, and shell-apps bring those two elements to the native app world. That’s something to celebrate.

Web Versus Native – Asking the Wrong Questions

There’s been a lot of talk lately about web apps versus native. It’s not that the question has ever gone away, but just over the past couple of weeks it seems like it’s been called out a bit more in blog posts. There was a Pew Internet report that covered some of the pros/cons of going web or native. Darryl Taft, one of my favorite press guys, did a writeup earlier this month on the landscape of web versus native and some of the companies involved in blending those two worlds. And then today I saw news about Mojito, a hybrid client-server solution from Yahoo, which is part of a wider initiative called Cocktails with the aim of “making web applications feel native“. And that got me thinking about the problems that people are trying to solve when it comes to web apps on mobile devices.

Web apps are in a tough spot when it comes to native, but they’re getting better. As I see it, one of the main problems with web apps is that they aren’t currently better. They’re cheaper, they’re faster (to write), and they allow you to target more platforms, but they’re not better. What’s even worse is that you could argue there are only 2 platforms for mobile that matter right now, Android and iOS. But it was the exact same situation back in 2003/2004 when the web really started coming into its own as an app platform and taking away from traditional native apps on the desktop. The one problem is that back then the web apps were better. They didn’t look as fancy and they didn’t run quite as fast, but there were few things that people needed to do that the web couldn’t do. I remember talking about AIR and mentioning things like drag and drop, file system access, and file type associations. Those were nice, but people didn’t really need them. What made web apps better for end users was the fact that they ran everywhere, were lightweight, always up-to-date and moved with the user so when they switched between the library, school, work, and home, their stuff went with them.

But fast forward to today. We never leave our mobile devices. They’re always with us. Sometimes we change contexts from our mobile device to a desktop/laptop/tablet (think email) but ultimately one of the things that made web apps so great, that they moved with the user, has been completely negated by smartphones. And increasingly, what web apps can’t do is much more important than what web apps couldn’t do 5 years ago. All of the sensors; GPS, Accelerometer, Camera, not to mention the data on the phone, things like contacts, that can be used to make things on the device so much more personal and completely change the experience. Some of the basic ones are available to web apps, and the specs are in place to get more, but there’s still a significant disconnect between what can be done with native apps on the device and what can be done on the mobile web.

To me that’s the biggest worry for the web on mobile devices right now. Sure, performance isn’t ideal, but as the browsers get better and devices get more powerful, that one will fix itself. The technology is there in the form of Canvas, SVG, great JS frameworks, faster JS performance. So the core interactive features work on these devices (with some performance caveats). But the benefits of the web are in many ways nullified by smartphones today. The web needs to come up with something that makes it better once again. And the deck is really, really stacked against it. Think of the distribution model of apps and in-app purchases. I think you could argue that those aren’t great for customers as much as they are great for content creators. Mobile apps are easier to monetize, easier to track, and easier to manage than the web right now. And on one hand, that’s fantastic. Finally designers and developers can directly make money off of their creations. But it’s coming at the expense of the web.

In order for web apps to thrive again the web community needs to start thinking about how mobile web apps can be better and more useful to customers than native apps. I have no doubt that it’s going to happen. How many times have you said to yourself “I don’t want your app, I just want to see the content” while browsing around the web on a mobile browser? So the sentiment from users is there, but for now the web just doesn’t provide enough value for users to get beyond the inflection point. So I’m hoping the conversation starts to move away from web apps not being fast enough, or “feeling native enough” to one of how web apps can be better than native from a user perspective. It’s going to be a fun conversation to watch unfold.

Building a Mobile-Themed Slider without jQuery Mobile

I’m generally a big fan of jQuery mobile. I think it’s an ambitious project and it’s got some areas that could be improved, but I’m glad we’re contributing and think it’s going to be a huge boon for mobile web applications as they get bigger and bigger. But building PhoneGap applications with jQuery Mobile is a bit problematic partly because the goal for the project is “Delivering top-of-the-line JavaScript and a unified User Interface across the most-used smartphone web browsers…” and partly because jQuery Mobile can be tough to really customize if you want a specific look and feel. One of the things I wanted for something I’m working on is a slider that is a bit more boxy than the traditional slider used with jQuery Mobile. Some of this might have been possible with customizing the jQuery Mobile theme but I wanted to see what it would take to build my own from scratch.

This example is part of an app that’s using Backbone.js so I won’t post a working example because the Backbone.js infrastructure makes it kind of tough to strip out just the toggle button part. I’ll post the whole thing later, but wanted to show the general process.

The Look and Feel

To set it up I wrapped a div tag around a select tag with a couple of options. The div tag provided the border so it ended up being the track that the sider went along. This makes it pretty easy to customize the look and feel while still being very nicely degraded into a regular HTML select box.

                         <div id="toggle" class="toggleoff">
                         <select name="activetoggle" id="activetoggle" class="selectoff">
                              <option value="all">All</option>
                              <option value="active">Active</option>
                         </select>
                         </div>

Initially both the div and the select start with “off” classes. At this point the CSS starts to take over and create a more slider-looking button. There is a cool -webkit-appearance property that can be used on the slider to give it some instantaneous look/feel. But for the most part I rely on -webkit-border-image to customize the look and feel of the slider button. The CSS for the toggle button itself, the div tag, and the off states give us a basic looking toggle with no real toggle functionality because it behaves just like a regular HTML select box.

Toggle button off state

select {
     -webkit-appearance: push-button;
     margin-top: 0px;
     margin-bottom: 0px;
     height: 50px;
     width: 155px;
     border-style: solid;
     border-color: #cdcdcd;
     border-width: 1px;
     color: #555;
       font-size: 25px;
       overflow: hidden;
     padding-top: 2px;
       padding-bottom: 1px;
     white-space: nowrap;
     text-align: center;
 
}
 
.selectoff {
     -webkit-border-image: url( ../assets/button.up.png ) 4 4 4 4 stretch stretch;
     padding-left: 60px;
 
}
 
#toggle {
     margin-left: 5px;
     margin-right: 5px;
     margin-top: 5px;
     height: 50px;
     width: 312px;
     -webkit-border-radius: 2px;
     -webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);    
     border: 2px solid #cdcdcd;    
}
 
.toggleoff {
     padding-left: 158px;
     background-image: -webkit-linear-gradient(#ffffff, #e7e7e7);
}

I have the benefit of using absolute positioning because I’m building this for an iPhone, but the CSS is pretty straightforward. I’ve got some padding-left properties so I can control how the text looks and where the actual toggle button appears within the div tag. This is why this particular strategy works. When I move between states I’m just going to change the position of the toggle button, I’m not actually doing anything with the select object itself other than changing how it looks and where it is. Here are the “on” classes.

 
.selecton {
     -webkit-border-image: url(../assets/button.down.png) 4 4 4 4 stretch stretch;
     padding-left: 30px;
}
 
.toggleon {
     padding-left: 0px;
     background-image:-webkit-linear-gradient(#bccead, #cbdfba);
}

Just a couple of small changes to gradients and backgrounds so that when our button is on or active, it looks like this:

Toggle button on state

Functionality

Now that the CSS classes are set up I used jQuery to first add/remove the classes I wanted and finally set the value of the select box programatically. As I mentioned, this is using Backbone.js so the code may look a bit odd.

          onMouseDown:function(event){
               event.preventDefault();
               if(this.displayingAll) {
                    $("#activetoggle").removeClass("selectoff");
                    $("#activetoggle").addClass("selecton");
                    $("#toggle").removeClass("toggleoff");
                    $("#toggle").addClass("toggleon");
                    $("#activetoggle").val("active");         
               } else {
                    $("#activetoggle").removeClass("selecton");
                    $("#activetoggle").addClass("selectoff");
                    $("#toggle").removeClass("toggleon");
                    $("#toggle").addClass("toggleoff");    
                    $("#activetoggle").val("all");                             
               }

My Backbone view has a variable, displayingAll, which I set to either true or false depending on what is currently visible. It helps track which classes need to be added/removed. But the first, and probably most important thing, is that I’m capturing the event and keeping it from doing anything. I don’t want the default select behavior at all so I can trap it and make sure it doesn’t keep doing the rest of its work. That means no pop up where the user can select values. Instead I go through and swap out the on/off classes to change the look of my button. Finally I use the val() method to set the value of the select so that what the screen is showing is the actual value of the select input.

So now the slider is working but we haven’t done any animation. So right now the slider just jumps back and forth. It works but it isn’t all that pretty. Luckily CSS3 is pretty awesome and we can leverage the very powerful -webkit-transition to help us out.

Animation

Animation for this example is insanely simple. Using the -webkit-transition CSS property we can listen for changes in the DOM on a specific property and whenever that property changes we can play a specific transition. The way I have set this up is that I’m changing the padding-left property between on/off classes so that’s the one we have to listen for.

Quick sidenote: I struggled with this for a bit. At first I was using the align property of the div to move the toggle button back and forth. That had the benefit of being able to scale better for multiple pixel-widths. The button would move back and forth just fine but there wasn’t a way to animate the align property that I found, which makes sense. So to do animation I had to use a value that could be animated and padding-left ended up being a decent option.

In order to get the animation to trigger we have to add a single CSS property to the #toggle div tag:

     -webkit-transition: padding-left 250ms ease-out;

So whenever the padding-left property changes (on a Webkit browser) a quarter of a second ease-out transition will play and move the toggle button back and forth. Under the hood we’re changing the value of the select so that if we have to rely on that value it’s all in sync while still creating a very specific look-and-feel for our toggle button.

I realize this isn’t entirely helpful without a working demo and I’ll work on getting a jsFiddle or something up to show it but I’m working on some other bits of the project and want to be able to share the whole thing when it’s done. One of the main things I learned: CSS3 transitions aren’t entirely intuitive when coming from the Flash world, but they’re very powerful.

Passing Data Between Pages in jQuery Mobile

Coming from Flex one of the things I’ve struggled a bit with is passing data between views in my jQuery Mobile applications. The template approach with Mustache worked really well, but it also had a lot of overhead. In fiddling around today I found a more hacky way that seems to work pretty well (though I think the Mustache route is still better). It relies on the fact that the pagebeforeshow method provides a prevPage property as part of its data object. That prevPage property is just a representation of everything in DOM of the previous page. That means it’s relatively easy to use selectors and that object to pass data to the new page.

The setup of my pages is as follows. My first page has a list of breweries, and each brewery page has a list of the beers that brewery uses. When you click on any of the beers, it goes to a form that can be used to rate the beers and provide some extra information about them. My goal was to prepopulate some of those forms with the beer data I already had. For instance I know the beer name, brewery, and style of each beer, so I should be able to prepopulate those, but they change for every beer so it has to be dynamic.

Within each page I defined a hidden div with two span elements with ids that represent the brewery name and brewery location (since they’re the same for every beer). Then within the beer list I have a hidden div that contains the beer name and the beer style. Here’s an example:

<div data-role="page" id="aleasylum" data-theme="e" data-add-back-btn="true">
     <div data-role="header">
          <h1>Ale Asylum</h1>
     </div>
     <div style="display:none">
          <span id="brewernameinfo">Ale Asylum</span>
          <span id="brewerlocationinfo">Madison, WI</span>
     </div>    
     <div data-role="content">    
          <ul data-role="listview">
               <li data-role="list-divider">Year Round Beers</li>
               <li>
                    <a href="#beerdetails">
                         <img src="images/hopalicious-thumb.gif" />
                         <h3>Hopalicious</h3>
                         <p>5.8% abv. Eleven separate additions of cascade hops give this American pale ale its lush citrus aroma and bold hop flavor without crazy bitterness. Hopalicious is available year round in six packs and on tap throughout the Madison and Milwaukee regions.</p>
                         <div style="display:none">
                              <span id="beernameinfo">Hopalicious</span>
                              <span id="beerstyleinfo">IPA</span>
                         </div>
                    </a>
               </li>
               <li>
                    <a href="#beerdetails">
                         <img src="images/madtown-nutbrown-thumb.gif" />
                         <h3>Madtown Nutbrown</h3>
                         <p>5.5% abv. Our nutbrown ale is velvety smooth with a rich caramel aroma. We blend seven different malts for just the right touch of sweetness and a creamy finish youÔøΩll really dig. Madtown Nutbrown is available year round in six packs and on tap throughout the Madison and Milwaukee regions.</p>
                         <div id="info" style="display:none">
                              <span id="beernameinfo">Madtown Nutbrown</span>
                              <span id="beerstyle">IPA</span>
                         </div>                        
                    </a>
               </li>

So in order to grab that, I just added an event listener to the pagebeforeshow method that uses selectors to grab the data. One of the critical parts is that jQuery selectors have an optional context property that can be set so that jQuery only selects from that context. In this case, since my pages are all using the same id names for the values, I need to set the context so that the selectors are only pulling from the previous page and not the entire document.

 $('#beerdetails').on('pagebeforeshow',function(e,data){
     var beername = $('.ui-btn-hover-e #beernameinfo',data.prevPage).text();
     var brewername = $('#brewernameinfo',data.prevPage).text();
     var brewerlocation = $('#brewerlocationinfo',data.prevPage).text();
     var beerstyle = $('.ui-btn-hover-e #beerstyleinfo',data.prevPage).text();
     $('#beername').val(beername);
     $('#brewername').val(brewername);
     $('#brewerlocation').val(brewerlocation);
     $('#beerstyle').val(beerstyle);
 });

The code above executes before anything gets displayed on the new page, grabs the values from the first page with the hidden div tags, and then sets some of the form fields to those new values.

It strikes me as a bit odd that there isn’t an easier way to do this, so it could be that I’m just not googling the correct thing and jQuery Mobile has something built-in to help with this issue. It does seem like this can be done by using URL variables, but what I like about this approach is that it’s a bit more semantic and there’s no required parsing of the URL string.

JavaScript Templating – Kind of Like ItemRenderers or Binding from Flex

One of the things I’ve been struggling with on the HTML/JS app I’ve been working on is how to get binding-like functionality. It seems like there are a few ways to do it, but the ones I looked at didn’t seem to fit with the general pattern of JavaScript and I wanted something a bit more elegant. Luckily, I just didn’t know what to look for, and once I came across templates, I realized I had found exactly what I wanted. Templates in JavaScript act like ItemRenderers but in my example I was able to use them to create a page, and then dynamically change the data on that page almost like I would if I were binding an object to a form in Flex.

And that’s almost exactly what templating lets you do. Here’s my example. I’m creating a list of beers, and when I click on one of those beers, I want to load a bunch of information about that beer in a form so I can make changes to it and save those changes to my database. With Flex Mobile I was able to do that pretty robustly because I can pass data between views very easily and bind elements in the second view to my data. With jQuery mobile, there’s nothing quite that fancy, so I had to rely on templates.

It turns out there are a ton of JavaScript templating libraries out there. Underscore.js includes a templating feature and looks interesting but I tried Mustache.js off the bat and found it pretty simple to use.

I started off with the template itself. In my case, it was a basic form that I called beer_detail.mustache

    <form action="#" method="post">
<div id="beername" data-role="fieldcontain">
            <span id="beerlabel">{{ beername }}</span>
            </div>
        <div id="brewername">{{ brewername }}</div>
        <div id="brewerlocation">{{ brewerlocation }}</div>
        <div id="beerstyle">{{ beerstyle }}</div>
<hr>
        <div id="quantity" data-role="fieldcontain">
<label for="quantityslider">Quantity: {{quantity}} </label>
<input type="range" name="quantityslider" id="quantityslider" value="{{ quantity }}" min="0" max="25"  />
</div>
        <div id="purchasedate" data-role="fieldcontain">
        <label for="purchasedatefield">Purchase Date:</label>
                <input type="date" name="purchasedatefield" id="purchasedatefield" value="{{ purchasedate }}"  />
</div>
        <div id="price" data-role="fieldcontain"><input type="text" value="{{ price }}"></div>
        <div id="cellardate" data-role="fieldcontain">
        <input type="date" name="cellarfield" id="cellardatefield" value="{{ cellardate }}"  />
</div>
        <div id="cellartemp">Cellar Temperature: {{ cellarTemperature }}</div>
        <div id="brewdate" data-role="fieldcontain">
        <input type="date" name="brewdatefield" id="brewdatefield" value="{{ brewdate }}"  />
        </div>
<a href="#pintley">This beer on Pintely</a>
        <button type="submit" data-theme="a">Submit</button>
        </form>

The double brackets {{ }} are all of the variable names that the template looks for so those will be replaced with actual data when the template gets rendered. I liked the similarity to Flex’s binding syntax.

One of the things you can do in jQuery Mobile is pass url variables, so for the first part of my application, I use a list of the beer names with a link to a page named beer_details.html that includes an id parameter that I use to look up the beer. In this example I’m using a Lawnchair database called “beers” and just calling the all() method to get all of the beers in the database. Then I iterate through those and build the list.

 
     beers.all(function(arrBeers){
          for(var i = 0; i<arrBeers.length;i++)
          {
               console.log(arrBeers.length);
               var listdiv = document.createElement('li');
                 listdiv.setAttribute('id','listdiv');
                 listdiv.innerHTML = '<a href="beer_details.html?id='+arrBeers[i].key+'">'+arrBeers[i].value.beername+'</a>';              
               $('#beer_list').append(listdiv);    
          }
          $('#beer_list').listview("refresh");
     });

The beer_details.html page itself just contains some skeleton code for jQuery mobile. The code will inject the template into the div id="content" tag. This way, all of the jQuery functionality stays with the application so it can use the back button, has the header/footer, etc and plays the transitions back and forth. So it’s pretty bare bones:

<div data-role="page" id="beerdetail" style="type-inline">
     <div data-role="header">
          <h1>Your Beers</h1>
     </div>
     <div id="content" data-role="content" align="center">
 
     </div>
     <div data-role="footer" data-id="foo1" data-position="fixed">
          <div data-role="navbar">
               <ul>
                    <li><a href="beers.html">Beers</a></li>
                    <li><a href="styles.html">Styles</a></li>
                    <li><a href="scan.html">Scan Barcode</a></li>
                    <li><a href="locations.html">Locations</a></li>                   
               </ul>
          </div>
     </div>
</div>

So now that the structure is set up, we can use Mustache to populate our template with data and inject the resulting HTML into the DOM. The first step is to set up the data object. In this code I parse the URL to figure out the ID of the beer, then use Lawnchair to retrieve that data. I’m listening for the pagebeforeshow method, but I’m not sure if that’s the best one. But it allowed me to get the data and change the DOM before the page showed, which is important for being able to render the template.

     $('#beerdetail').live('pagebeforeshow',function(e) {
          var beerID;
          beerData = {};
 
 
          var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');    
 
          for(var i = 0; i < hashes.length; i++)
          {
            hash = hashes[i].split('=');
            if(hash[0] == "id")
            {
                 beerID = hash[1];
            }
          }                 
 
     });

Once I have the beerID, I can use LawnChair to grab the information. Then I can use that object and pass it to Mustache to build the template. The Mustache library uses a .to_html() method that takes a reference to the template and the object that holds the data, in this case beerData. In the example below, there’s a bit of chaining going on. First I have to get the data, then when that is returned, it calls a function that will go out and load my .mustache template using Ajax, and finally, when that page is retrieved, I call Mustache.to_html() to get the HTML and then inject that HTML into the content so it will render correctly. This code goes inside the pagebeforeshow event handler.

          beers.get(beerID,function(obj){
               beerData = obj.value;
               $.get('templates/beer_detail.mustache',
                    function(data){
                         template = data;    
                         var renderedhtml = Mustache.to_html( template,beerData);
                         $("#content").html(renderedhtml);    
                    });
          });

And voila! Now when we click on a beer from the list, the data gets inserted into the template and when we move back and forth the data will update as we click on new beers.

This is much, much easier than trying to go through the DOM and insert/modify the form variables and also lets us potentially use different templates depending on the beer I choose. So far I’ve found templates to be helpful for getting around concepts like binding in HTML/JS.

I’ve gone ahead and put this project up on GitHub. It’s kind of a disaster at this point, since it’s basically my learning project, but you can see how this was done.