These are my actions. These are my words.

Fixed positioning in Mobile Safari

11/16/2010: It’s been a long time since my fixed positioning script was released. I’m very pleased that it was the precursor for much more robust solutions to this problem. Please continue on if you’d like to read through the history of this hack. If you’re looking for a real-world solution please take a look at one of the following, ranked (subjectively) in order of scroll performance:

  • Sencha Touch – A complete framework with fixed scrolling, custom widgets, and more.
  • YUI Scrollview – Standalone solution built on YUI3
  • iScroll – Completely standalone, no library dependencies

Update: An anonymous genius in the comments suggested using translateY instead of top for the animation. After some edits I’ve updated my demo, and it flies! The scrolling animation is smooth as silk. Apparently Webkit transforms are the only hardware-accelerated animations at this point. Thanks, random dude on the internet!

Update 2: This code is released to the public domain. You can use, modify, remix as you see fit.

Behold, fixed positioning on iPhone! http://doctyper.com/stuff/iphone/fixed/

Here’s a video for those without iPhones. This is running in the iPhone Simulator bundled with the SDK. Note that the animation is much choppier on an actual iPhone.

With the release of iPhone OS 2.0 came some great improvements over previous Mobile Safari versions. CSS animations are in (though buggy), as well as native touch events like touchstart, touchend, gesturechange, etc.

I played around with these new goodies while hunting for improvements to build into Pickleview. The most fascinating change to me was that you can now prevent the default behavior of elements with a simple preventDefault() call. It allows a user to drag an element around the screen without having to worry about the viewport wobbling about.

I grew curious as to what I could specifically call this on, and started testing out several elements. Turns out you can preventDefault on everything in the DOM, including the body element. This seemed incredibly useless for no other reason than the terrible usability it would bring if you couldn’t scroll the viewport. Then the proverbial light bulb went off: fixed positioning!

First, let’s recap why fixed positioning does not work off-the-bat. Mobile Safari uses a viewport to show you websites. Imagine a book in front of you. Take a piece of paper, cut a 320×416 square in it, and lay it over the book. To read the book, move the paper around and position the hole over the words you want to see. This is exactly what Mobile Safari’s viewport is doing. When you flick and scroll, you’re moving the viewport around while the website behind it stays static.

This renders fixed positioning null and void on iPhone. An element that has its position fixed is affixed to the body, not the viewport. So it is actually working as intended, though most people would prefer it attached to the viewport.

There are workarounds in the wild, but these are inelegant. You can reposition an element onscroll, but a scroll event in Mobile Safari is only fired after scrolling has stopped. This results in an evident “glitch” since you have to a) flick to your desired position, throwing the element off-screen, and b) wait for the element to reappear in the viewport after scrolling has stopped.

By disabling the default scroll behavior on the body element, you essentially glue the viewport down to its initial starting point, where it’s unable to go anywhere. This limits the viewport to exactly 320×416 pixels of space to show you. In this state, you have a perfectly useless experience.

This is where it gets interesting. In order to re-enable scrolling, I needed to only make the content area scrollable (think iframe, with header and footer above and below it). The touch and gesture events gives access to X/Y values, as well as timers and offset values. So by logging these and incrementing the top offset of the content area, we can create a scrollable block that does not affect the header or footer elements. A little spit and polish later: voila!

It’s pretty evident from my proof-of-concept that CSS animations need a lot of work. They’re promised to be “hardware-accelerated”, but there’s little proof of this. Most animations glitch, some to the point of non-use. The scrolling isn’t particularly smooth and even something as simple as animating a ‘top’ CSS property takes its toll. Still it’s usable, though I hope later Mobile Safari builds will address these issues.

If you’re interested, I’ve bundled together the source files for my proof-of-concept. Grab ‘em here.

Breaking out of a forEach loop

An email going around the client-side mailing list at Schematic casually mentioned forEach loops. The sender liked them, but tended to avoid them because there was no way to break out of one.

Naturally, this sent me on the hunt to see if it was at all possible. A furious Google search led me to a comment by Dean Edwards (who else?). He suggested throwing yourself out of the loop and wrapping the throw in a try catch statement to silence the throw. Like so:

var array = [1, 2, 0, 3, 4, 5];
try {
  array.forEach(function(item) {
    if (item === 0) {
      throw new Error(); // Simulated break
    }
    console.log(item);
  });
} catch (e) {}

That does the trick. Fellow developer/comrade Lenny Burdette pointed out that this was exactly the method Prototype uses to break their own custom loops.

But of course, there’s caveats. With Prototype, you merely have to call $break to have it automate this for you. With Flow, you’re exposed to the elements and need to handle it yourself. It’s a neat trick, but quite honestly it’s not very user friendly, and looks a bit unwieldy as a workaround.

I browsed the forEach documentation and went through possible solutions. One was to extend forEach and include a custom break function in it. But I decided against this for a few reasons. One, it would violate the rules (#3, to be exact). Over-extending a native function would bring more hurt than it would good. Second, Safari 2 has a problem with extending forEach, so it wasn’t a viable solution either.

But I had a hunch. What if I simulated a break by splicing off the remaining objects in the array, thereby terminating the loop entirely? I gave it a try:

var array = [1, 2, 0, 3, 4, 5];
array.forEach(function(item, i) {
  if (item === 0) {
    array.splice(i, array.length - i); // Simulated break
  } else {
    console.log(item);
  }
});

Success! The loop terminates, because there are no more objects to continue to. There’s just one problem: there are no more objects to continue to. It mutates the array, so it’s not reliable if you need to reuse the array. You’re limited to using it only once, or having to rebuild the array.

Ah, but what if you splice the array, and immediately concatenate it? Would it have the same effect and stop the array in its tracks?

var array = [1, 2, 0, 3, 4, 5];
array.forEach(function(item, i) {
  if (item === 0) {
    array = array.concat(array.splice(i, array.length - i)); // F-f-f-forEach breaker!
  } else {
    console.log(item);
  }
});

Double success! In this example, the array is spliced from the current index point, and all remaining objects are dropped off, ending the loop. The magic happens when we rejoin the array using concat, and reassign the newly constructed object to the array variable. The array is mutated back to its original form, and you’ve broken the forEach loop.

Still, it’s not as satisfyingly simple as a break, is it? Well, we can’t call a break, but we can get close. The next Flow revision will contain the exit Array extra, which will provide you with a keyword (or, as close enough a keyword as I could get) to break a forEach loop:

var array = [1, 2, 0, 3, 4, 5];
array.forEach(function(item, i) {
  if (item === 0) {
    array = array.exit(i);
  } else {
    console.log(item);
  }
});

Flow 1.0.2

I just pushed release 1.0.2 out the door.

Bug fix:

Flow will no longer choke with SWFObject.

Early this morning I received a report about Flow not playing nicely with SWFObject. After debugging, it turned out it was a case of doing too much.

SWFObject correctly cleans up after itself in IE by removing its generated code on unload. The conflict appears because Flow does the same with its code, going as far as eliminating all extended element properties.

So when SWFObject tried to removeChild, it returned null because Flow extends that property, and by the time SWFObject got to it, it was already wiped out.

Flow now merely restores an extended property back to its original implementation, rather than nullifying the property. This will fix the error.

Feature:

dispatchEvent is now implemented in Flow. You can use it to fire events on elements from another element. Confusing? Here’s an example:

var test = document.getById("test");
test.addEventListener("click", function() {
    // console.log(this.id);
}, false);
 
document.getById("dispatcher").addEventListener("click", function() {
    test.dispatchEvent("click");
}, false);

You can pass any event type and it will fire all events coupled with that type.

As usual, you can download the Flow framework at http://flowjs.com

Introducing Flow

This is a post I’ve been wanting to write for months now. For the past several months I’ve been spending my free time toiling over a personal project of mine.

It started with Dean Edwards and his release of the Base2 library. It scratched an itch that I’ve had for years: I wanted the ability to use the DOM API (Level 3) in all modern browsers. Base2 has since seen a second revision and is even more powerful than before. (Aside: Dean Edwards’ is a freaking genius.)

But I wanted more. I wanted a hybrid API that would allow me to use the standard API, but would also contain helper functions, shorthand notation, chainability, etc. So I got to work.

After eight months of development, trials, tears and tribulations I am pleased to announce the initial release of The Flow Framework.

Flow aims to fix and enhance the DOM Level 3 API. Flow extends API functionality to browsers that currently don’t support it. Additionaly, it adds powerful functionality on top for the best bang for your JavaScript buck.

A sample of the functions it implements cross-browser:

  • getElementsByClassName / getElementsByAttribute
  • addEventListener / removeEventListener (with DOMContentLoaded support)
  • preventDefault / stopPropagation
  • addClass / removeClass / replaceClass
  • querySelector / querySelectorAll
  • shorthand notation (getById, getByTag, getByClass, etc)

Here’s a snippet of what can be accomplished with Flow:

Find all: ul.checked li

With Flow Core

var uls = document.getElementsByClassName("checked").filter(function(e) {
  return e.nodeName.toLowerCase() == "ul";
});
var lis = [];
uls.forEach(function(ul) {
  ul.getElementsByTagName("li").forEach(function(li) {
    lis.push(li);
  });
});

With Flow Extend

var lis = document.getByClass("checked").filter(function(e) {
return e.elementName() == "ul";
}).getByTag("li");

With Flow Query

var lis = document.querySelectorAll("ul.checked li");

Want to open external links in new windows via JavaScript?
document.getByAttr("rel", "external").setAttribute("target", "_blank");

Want to return false on those pesky blank-anchor links?
document.getByAttr("href", "#").addEventListener("click", function(e) {
  e.preventDefault();
}, false);

There are more code samples, documentation, unit tests on the official site. Be sure to download a customized Flow build and try it out!

For those that want to take a gander at the code, you can check out the source on Google Code: http://code.google.com/p/flowjs/.

There’s already a website using Flow in the wild. South Park Studios was unveiled a couple of months ago, and it’s been chugging along since. Unfortunately I was under gag order at the time while the final details were being hammered down. Now I can officially state that it’s using Flow and lovin’ it.

Many, many thanks to Schematic for supporting the release of this library, and to the many Schematicans who freely contributed to the library.

Thanks are also in order to the great JavaScript programmers who’ve turned us all on our heads: John Resig, Dean Edwards, Robert Nyman, Tino Zijdel, Sergey Ilinsky and countless others.

Pickleview 1.5

Ahh, smell that? It’s the sultry scent of Major League Baseball returning at last!

After a furious weekend of code, I’ve pushed out Pickleview 1.5. What’s new? I fixed bugs, updated settings, added features and threw on a fresh coat of paint.

The improved Pickleview takes advantage of some minor iPhone goodies, and preps itself for the upcoming 2.0 software. It runs smoother and loads quicker. Good news for those EDGEing along at ballparks.

You can also do this now: http://pickleview.com/?dodgers

Check it out and enjoy!

Footalk

Greetings!

It’s been a while, but you know the drill: Long hours + Longer todo lists = No time to post.

To kick off 2008, myself and fellow blogger/nerd/geek Micah Cambre sat ourselves down and podcasted for the very first time. It was simultaneously thilling and horrifying. You can find our labor of love at Footalk.net. Please enjoy.

Footalk!

Fumble U

So I’ve been hard at work on side projects and regular work, but not busy enough to continue my love affair with iPhone.

Hot on the heels of the Fumbleview beta release comes Fumble U. It suffers from the same quirky bugs as its big brother, but it’s very stable.

I had decided to wait until Fumbleview reached 1.0 before releasing another app, but fortunately for me it only took a fraction of what I thought it would to tie into the college football database. It was still a minor feat, since there are a metric ass-ton of division 1-A teams. Ultimately I had to devise a method to fit all top 25 teams in the limited space I have.

Focus will switch to Fumbleview until I tie up its loose ends. Afterwards it should be a simple process to catch Fumble U up.

Support all mobiles? Start implementing standards and I will.

Prelude.

I’ll keep this short, as this comes down to very simple points.

I don’t block anyone from visiting Pickleview or Fumbleview. You can view it in any browser, mobile or desktop. I don’t sniff for iPhone, and lock out others. I don’t do any special CSS magic to block it from view. Rather, you get a much enhanced experience if you view the apps on iPhone.

My web apps will display and function perfectly in any browser that supports these standardized methods:

  • XMLHttpRequest();
  • addEventListener();

That’s it. Too much to ask for? Apparently.
(Note: Blackberries run IE.)