Adding iPhone style swipe to delete button to a listview component in jQuery Mobile

Filed under: jQuery Mobile

comments (49) Views: 76,193

Update: I've released a jQuery plugin called swipeButton which you can simply drop into your project.

While developing the mobile website over at Goba.mobi this week I decided that I wanted to add a little flair and drop in a "swipe" menu allowing users quick access to actions that they would normally have to view the details page to use. Luckily jQuery Mobile makes it easy...so with just a little CSS, a little JavaScript, and some built-in events I made it happen; in just one day. Here's how I did it.

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.

Here's the listview code, note that the button itself isn't hardcoded. Because the swipe action isn't something that older devices can recreate I felt safe in making this a pure JavaScript/CSS solution.

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.

Amazon logo

If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!

Related Posts


comments powered by Disqus