f

unk rock


iPhone Touch Events in JavaScript

August 19th, 2008

Yesterday I gave a presentation at the San Francisco JavaScript Meetup about the new JavaScript touch events API in iPhone 2.0. I thought I’d share the slides, in case people were interested in viewing them after the fact.

I owe a great deal of thanks to Neil Roberts from SitePen, who’s post on the topic was my main source of information. My co-founder Tom Robinson was also helpful, thanks to his iPhone light-table.

One of the interesting things I was able to talk about was reusing existing mouse based libraries with the iPhone by using touch events to simulate mouse events. The basic idea behind it was to address the fact that mouse events don’t work particularly well on the phone. It’s unpredictable when you’ll get them, if at all (you won’t if you attach only to document, for example). Mousemove in particular doesn’t work in any meaningful way.

In contrast, the touch events are completely predictable and reliable (excepting the existing bugs). We can use these events to simulate the existing mouse events with a fair amount of accuracy. In particular, when one finger is down on the screen, touchstart, touchend, and touchmove correspond nicely with mousedown, mouseup, and mousemove. There’s some difference in the way mousemove works, since we can’t get mousemove events when the finger is not touching the screen, but this is an acceptable trade off. It doesn’t make sense on the iPhone anyway because there’s no persistent cursor.

I took this jQuery based drag and drop example to see if I could get it working on the iPhone without modification. Here’s the working iPhone demo. The only existing code that I modified was some CSS to make the page fit nicely on the iPhone screen, and a viewport meta tag. The added code to get drag and drop working is really simple:

function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = “”;
    
    switch(event.type)
    {
        case “touchstart”: type = “mousedown”; break;
        case “touchmove”:  type=“mousemove”; break;        
        case “touchend”:   type=“mouseup”; break;
        default: return;
    }
        
    //initMouseEvent(type, canBubble, cancelable, view, clickCount,
    //           screenX, screenY, clientX, clientY, ctrlKey,
    //           altKey, shiftKey, metaKey, button, relatedTarget);
    
    var simulatedEvent = document.createEvent(“MouseEvent”);
    simulatedEvent.initMouseEvent(type, true, true, window, 1,
                              first.screenX, first.screenY,
                              first.clientX, first.clientY, false,
                              false, false, false, 0/*left*/, null);
                                                                            
    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init()
{
    document.addEventListener(“touchstart”, touchHandler, true);
    document.addEventListener(“touchmove”, touchHandler, true);
    document.addEventListener(“touchend”, touchHandler, true);
    document.addEventListener(“touchcancel”, touchHandler, true);    
}

I’ve captured the touch events and then manually fired my own mouse events to match. Although the code isn’t particularly general purpose as is, it should be trivial to adapt to most existing drag and drop libraries, and probably most existing mouse event code. Hopefully this idea will come in handy to people developing web applications for the iPhone.

Update: In posting this, I noticed that calling preventDefault on all touch events will prevent links from working properly. The main reason to call preventDefault at all is to stop the phone from scrolling, and you can do that by calling it only on the touchmove callback. The only downside to doing it this way is that the iPhone will sometimes display its hover popup over the drag origin. If I discover a way to prevent that, I’ll update this post.

Second Update: I’ve found the CSS property to turn off the callout, “-webkit-touch-callout”. You can read about it in Apple’s documentation.

Ross at 10:44 am | Posted in Apple, Projects, Technology, Web | Comments (9)

Aftermath of 280 Slides

June 19th, 2008

We launched 280 Slides two weeks ago, and it’s been a great experience. After putting five months of non stop work into it, it’s a good feeling to be able to point to it and say “That’s what I’ve been doing.” It’s also fantastic to be getting all kinds of feedback from people who like (and dislike) the application. It really does help you focus on what matters to people.

We’ve had some great press mentions too (both Slides and Cappuccino):

TechCrunch
Ajaxian
TUAW
Guardian.co.uk

And quite a few blogs. (and twitter)

There’s also been a fair amount of confusion regarding MobileMe and SproutCore. Just to clarify, MobileMe is not based on Objective-J or Cappuccino, and 280 Slides is not based on SproutCore. 280 Slides isn’t part of MobileMe, and we have no affiliation to Apple. Oh, and there are three of us, not two.

Ross at 3:49 pm | Posted in Projects, Technology, Web | No Comments

Safari’s Web Inspector

April 21st, 2008

The WebKit team announced the list of participants they’ll be working with on this year’s Google Summer of Code today. Of particular interest to me was this applicant. Anyone who does serious web work can attest to the difficulty of debugging anything in Safari, meaning that most web developers have pretty much given up and develop in Firefox full time. This is such a shame, since Safari is almost universally a better browser — it’s faster, it supports more of the things I care about, and for all the reasons Gruber listed (and more), it’s the browser I use personally.

The thing is, the WebKit team has known for some time that they have serious issues with debugging. In fact, I’ve been told better debugging support is the number one requested feature. We saw some attention paid to the issue with Drosera, but it turned out to be nothing more than lip service. Our code brings Drosera to a halt in seconds, as do most of the complicated sites we’ve tried it on. Safari desperately needs a profiler, stack traces, and someday step through debugging. Even beyond advanced tools like what Drosera promised and what Firebug has, WebKit fails on some of the most basic levels. This bug is damning. It should be a P1. Any callback function (read: any AJAX request, event handler, etc.) fails to report the error it encounters. Almost every error in our code base is reported as “undefined” by Safari.

Keishi, you’ve got an important job ahead of you. You’ve been tasked with doing what might be the most important thing the WebKit project has done in a long time. Safari has been kicking ass in pretty much every other area, but it’s ignored by web developers precisely because it’s so cruel towards them. I wish you the best of luck in doing this project, and if you’re looking for feature requests, I’ve got at least a million. At the top of my list? Solve the most important limitation of Firebug — not properly recognizing anonymous (eval’d) code. I have high hopes for what this could be by the end of summer, and I’ll definitely be following the progress.

Ross at 1:12 pm | Posted in Apple, Technology, Web | Comments (1)

Lions in a Cage

March 23rd, 2008

Paul Graham wrote an essay last week where he compared employees of big companies to lions in a cage at the zoo. Sort of.

I was in Africa last year and saw a lot of animals in the wild that I’d only seen in zoos before. It was remarkable how different they seemed. Particularly lions. Lions in the wild seem about ten times more alive. They’re like different animals. And seeing those guys on their scavenger hunt was like seeing lions in a zoo after spending several years watching them in the wild.

Technically, Paul is comparing the startling impact of seeing lions in a cage after seeing them in the wild to his experience seeing these employees (‘those guys on their scavenger hunt”) after spending the last three years watching founders at Y Combinator. Nevertheless, the article (and this quote in particular) caused quite the controversy around the Internet (or at least around the tiny subset of the Internet that reads Paul’s essays, myself included).

It’s not hard to read that last sentence and interpret it as a claim that working for a big company is like being an animal in a cage. I don’t think it was Paul’s intention to say exactly that, but even if it were, I think the point is immaterial to the essay as a whole. It is, at its worst, an exaggeration to prove a point, something I think we can all admit to doing from time to time (indeed it’s something that great writers have always done).

The central thesis of the essay is that being an employee is harmful to individual programmers, and that being a startup founder is a better way to live. In fact, he states this explicitly:

Watching employees get transformed into founders makes it clear that the difference between the two is due mostly to environment—and in particular that the environment in big companies is toxic to programmers.

It seems to me that Jeff Atwood’s (and others) primary argument is that some employees have actually enjoyed working for big companies, himself included, and Paul is thus making a generalization that is not true. But Paul makes no claim about employees being unhappy. Though he doesn’t address the topic directly, he sets up the entire essay by saying that he isn’t talking about some special property of founders, he believes there is something missing from the life of an employee. The absence of something you don’t even know you’re missing is hardly likely to make you unhappy on its own.

When I left Apple, it was not because I was unhappy. I was working with phenomenal individuals on an interesting set of problems. I left because I was excited about the potential of our company. And despite having worked in a great environment, at an amazing company (Apple was my dream job), I feel that all the things Paul said about founders at Y Combinator ring true. I am definitely “more worried and happier at the same time.” So is John Gruber. When I had lunch with my old team on Friday, at least one person mentioned noticing the change as well.

I think Paul’s food analogy was a much better one to illustrate the point. There is plenty of science to back up the claim that most of the food we eat is unhealthy (and I’m just as guilty as anyone else), however the position is still controversial. People who avoid highly processed foods, high fructose corn syrup, refined sugar, white flour, and lots of red meat are generally healthier. These people will tell you that they are happier, and more active, and that it’s directly related to what they eat. Yet these people are also ridiculed by the majority as fringe environmentalists, lunatics, or hippies. Most people will live their entire life eating what everyone else does and will be perfectly happy doing so, but until you’ve actually gone out and changed your lifestyle and started eating “like a hippy,” you can’t possibly know whether or not you would feel better than you already do.

Eating like a hippy isn’t for everyone and neither is starting a startup, but a lot more people would thrive in a startup environment than you think, just as a lot more people really would feel better eating like a hippy. Not everyone will be convinced by Paul’s essay, and that’s okay. There are parts I disagree with as well, in particular with respect to getting some experience at a company before starting your own. As a whole, though, the essay is consistent with what I’ve experienced at Y Combinator, and other founders I’ve talked to agree.

Ross at 5:45 pm | Posted in Life, Technology, Web | No Comments

Optimus Maximus

February 22nd, 2008

Those of you who read Engadget, or follow tech blogs, or are otherwise incredibly geeky, have surely heard of the Optimus Maximus. Vaporware for years, Engadget has finally got their hands on one. The verdict?

Typing on it, well, sucks.

This is a shining example of people building tech products that appeal to geeks, but overlooking the most basic, important functions. Sure, it’s nice to look at, and it sounds really cool to hot swap your keys. But, if it can’t type, then what good is it to anyone? What, I’m supposed to have two keyboards at my desk? One for typing, and one for … having little pictures? There’s a reason the iPhone is also a great phone.

At $1500 it might not matter, because only crazy people are going to buy one anyway.

Ross at 10:16 am | Posted in Technology | No Comments