Adding iPhone style swipe to delete button to a listview component in jQuery Mobile
Filed under: jQuery Mobile
comments (49) Views: 85,871
Update: I've released a jQuery plugin called swipeButton which you can simply drop into your project.
If you'd like to see this code in action, check out the demo. The original concept was to allow a user to cancel an event that they had created. The appearance would be similar to the iPhone's standard swipe to show a cancel button action pictured here.
I'm tying into jQuery Mobile's pageshow event. This fires when each new page is loaded, and ready to display. Because I'm only adding this behavior to certain pages in my app, I'm also going to check the target id. This id is found at the root of every jQuery Mobile page. In the example above, the id is "swipedelete". The code below is commented, but I'll point out a few things of note. It might seem like a duplicate, but $('.aDeleteBtn').remove(); should actually be in there twice. Once when this "page" gets focus, and again, when someone swipes to the right.
The final piece we need is the CSS. jQuery Mobile makes great use of themes, but they don't have a red theme yet. So I modified one of their built in themes to allow for the red "delete" button we're looking for.
I'll be writing a tutorial on theming jQuery Mobile in the coming weeks, but for now you just need a few tidbits. jQuery Mobile is built around single letter themes. Currently they run from a-e. Every class in the jQM repertoire is built around the .ui prefix. Everything else spreads out from there. To add, or change the theme on any element, simply add the appropriate class, and change the letter on the end until it looks like you want. If it doesn't then check back for my theming tutorial to get it looking spot on!
I hope that this swipe to delete tutorial helps you out. Remember that you can take a look at the finished product if you like. In the next few days I'll be writing a second part to this article showing you how to create an entire "swipe menu" like one found in Twitter for iPhone.
If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!