Wednesday, November 30, 2011

windows kudos, osx phoodos

So here's something from Windows that I think belongs in a UI Hall of Fame. It's the Location bar of the Windows 7 File Explorer:

It shows you the current folder location in a logical, breadcrumb manner. Hover over part of the current location:




BAM! It fades into a button, and you can click it and hop the folder's view to that location. That's brilliant! (Somewhat less brilliant because it's getting more obscure: (AKA I didn't realize it 'til just now:) click the arrow to the right to hop to siblings of that folder.)

(UPDATE: OSX has a "Show Path Bar" option that brings up a similar breadcrumb-y view. You can even hop up to any of the parents, but you have to double click, which seems unfriendly to me.)

But the really great part is clicking on the location bar just outside of the visible path:




DOUBLE BAM! That is a text version of the path, pre-select for your Ctrl-C copying convenience. Now, even if you're not using the dear old command line much, it's still hugely useful: in any standard file dialog, you can paste that into the filename, press return, and now you're ready to save your file in that location. (OSX sort of does something similar if you start typing with a slash, but it's heart isn't really in it.)

So I don't know if that is a "poweruser" usecase, but I find it hugely intuitive and fast, fast, fast. Now, there are imperfections in this system of text versions of the path-- if you click for a file path when you happen to be doing a search, the result is an unreadable mess that you can't really usefully paste anywhere. But there are other nice touches to the widget that I'm not even going into here.

Speaking of standard file dialogs, here's a bit of crapness from OSX. Here's a file save as dialog.
So that "Where" interaction, showing a small list of common spaces you might want to Save To,  is something relatively new in UI land. Windows does it too, but the dropdown menu is used to control a larger folder view. So you can jump to one of the standard areas, and from there, say, create a new folder, or go up a level, or do the usual folder manipulations:


And so I figured that that functionality must be somewhere in the OSX file dialog, that I could save somewhere other than exactly one of the pre-ordained file locations... but where? How do I get to it?

Answer: that small triangle to the right of the filename. That changes the look of the dialog to this:

That's better... but why is it so hard to find and why is it like that in the first place? I like thinking through the challenges UI designers must have faced, because sometimes you realize there's a complicating detail... Why isn't the more flexible view part of the dialog to begin with? I guess to simplify things, stop people from getting overwhelmed with options, while satisfying an 80/20 (70/30?) rule about where a user wants to put something. So why is it arrow to the right of the filename, and not the "Where" dropdown? (It is functionality related to the location, not the filename...) I guess because the "Where" dropdown changes form enough in the new mode that the up arrow to put it back might get lost. But it seems unintuitive to me. (Meaning I had to go ask a more experienced OSX user where to go for it.) Combine it with the way I've lost my ability to copy and paste a path here, and I have to say, I find the Windows experience superior.

(I know Mac fans stuck working on Windows probably miss the 3 column view for its folder viewer, along with the too-cool-by-half "Cover Flow", but for me, I'd rather have the ability to easily transfer path information around. UPDATE: OSX has this functionality, by dragging the icon at the top of a Finder window onto a dialog. Even given my lack of experience with OSX, this seems a little fiddly to me, where I might think I was trying to move the folder to whatever location the dialog was open to.)

Another OSX-ism I find irksome: the default Preview program is great for quick viewing, except it has no concept of "go to the next file in this folder". What's weird is that the basic functionality is in place: it does the right thing if you drag and drop a bunch of files onto it once, or select the files and right click and hit "Open with Preview.app" (Sorry, I was wrong: Preview doesn't support drag and drop.) I have had friends who are bigger fans of OSX say I was expecting the wrong thing, that file systems are arbitrary ways of holding a bunch of files anyway, that a more realistic usecase is just using iPhoto for all this stuff, but, whatever man. It was a detail I think they could have done gotten better, and it makes my life on OSX less easy than my life with Windows.



Monday, November 28, 2011

why windows' taskbar beats osx' dock

OS preference is, generally, a subjective thing. With the gradual ascendancy of Apple underway, I'd like to take a second and analyze how the two OSes relate, and where I think Windows has done a consistently better job. This will reflect some of my personal preferences (and, possibly, the way my mind has been warped by 15-odd years of Windows-isms-- any analysis like this has to recognize that we tend to like what we find familiar) but I will point to some objective differences between the systems.

First, a random note on the screenshots: I'm one of those quirky people who puts the app controller on the side of the screen. I wrote up why on my blog about 5 years ago: there are a few advantages, first and foremost is how it makes better use of the "widescreen" format laptops and monitors now sport (I mean, have you seen how short the screen is on a 11" MacBook Air?)

So to the left is the Windows taskbar and the right is the OSX dock... both have their graphical bells and whistles. Windows (at least as of 7) has some translucency going on - on my work machine it's really sophisticated, with an "active window" highlight color and some pretty light effects as the mouse passes over it. The Dock has that terrifically fun "magnify" effect, where the icons fluidly grow and shrink as you pass the mouse cursor over it.

The primary difference between these two bars is this: The Taskbar is Window based, the Dock is Application based. This is why I think the Windows approach is superior for a multitasking operating system: each window maps to a task, a bit of state I might want to return to, and the Taskbar offers a passive, unobtrusive reminder of each window and a way to get back to it. (Kind of a dynamic "todo list") With the Dock, each icon is an application. There is no direct jump to a given window, just that application. (OSX offers some other paradigms for getting back to where you were, more on that in a bit.)

Let's start with Windows. Every window gets its own place in the task bar... (before Windows 7, the "launch a new program" icons were either hidden behind the Start button, or later, on a little specialized "quick launch" piece of the taskbar. Nowadays you always have the option of "pinning" an application to the taskbar, which comingles the running and launching icons.) The difference between a Window of a running program and an icon to launch a new instance is obvious: the former is a button with a caption, the latter is just an icon. (The disadvantage is launching a new window of a running program from the taskbar is a bit awkward, it's the first option on the right click menu. It's not that big of an issue thought because browsers and most document editors use File|New or Ctrl-N to open a new workspace. UPDATE: WorldMaker points out you can middle click on a running task button to pop open a new window.)

With the Dock, the visual difference between a running and launchable program is minimized: a small white dot. Click on the icon and its windows move to the front. Again, to me there's a huge difference between a running program (carrying state I want to be reminded of or get back to) and a launchable program (which is a clean slate) and so I find Windows' approach to be superior.

This App-centric approach carries through to the quick switching. With Windows, I hit alt-Tab and I see a sorted list of my windows. OSX has a similar function, but again I'm looking at placeholders for whole apps, not a window at a time, once I switch to the right app I still have to find the window I'm thinking of. I know there are different apps to adjust the OSX environment, but I think getting the defaults right is crucially important-- having to relearn how to get around a friend's computer running the same OS because they don't have the same "fix" installed stinks.

It could be argued that I'm doing it wrong, expecting OSX to act like Windows instead of adapting to what OSX offers. For a long while OSX has had exposé, a single button that temporarily resizes and repositions all of your windows (or makes snapshot thumbnails, based on how you think of it) so that they are all visible at once. OSX Lion's Mission Control furthers that paradigm. While I might be getting old and curmudgeonly, I don't like exposé as much as Windows' system, in part because it lacks the "quick bounce back" of alt-tab, where a quick tap of alt-tab brings me back to what I was last working on (Windows has a really good "most recently used" algorithm for tasks, an easy to miss but hugely important detail that Just Works.)

UPDATE: OSX does have cmd-` (very easy to find above cmd-tab, kudos for that choice) that cycles through open windows of the current application. But this interaction is application oriented, you can't gracefully leap back to what you were doing in a different application like you can with Window's alt-tab. 

(I guess I should say, Windows 7's defaults are a bit different than what I'm describing here... I set Windows to "Never combine" Taskbar buttons, and so I don't see the roughly exposé like thumbnails Windows makes now.)

This differences harken back to one of the oldest differences between Windows and MacOS-- with Mac, there's one place on the whole screen where the "File" menus will appear: each app takes over that space. (It's kind of ironic that it took OSX so long to get fullscreen mode right.) This kind of points to the idea of Mac as "information appliance"-- the whole machine is dedicated to that app. On iOS I find this perfect and relaxing, but I find it irksome on a multitasking system. (I know people argue that there are advantages to the menubar-on-top paradigm of Mac, that you always know where to look, and your mouse can target the menu faster, but for me those bonuses are outweighed by having to figure out which menu bar applies to which window.)

I have some more thoughts on Windows vs OSX, but that can wait 'til next time...

Monday, November 21, 2011

room to write

Apologies for the less-than-fully-assed entry that follows:

I thought a pretty common task for jQuery would be to make a textarea automatically expand as content was added into it. And a bit of googling shows that a number of people have taken a stab at it. But it looks like no one has gotten it quite right, and I don't have enough time and energy to fix that.

The best I found is padolsey's jQuery.fn.autoResize. Once you include the .js file usage is trivial:

<script>
$(document).ready(function() {
  $('textarea').autoResize();
});
</script>

There are some configuration options as well.

I'm not 100% enamored of it: if you edit the value manually (like by calling $("textarea").val()) , the thing is not resized, and while it has basic coverage for resizing when users paste in text, it gets a bit wonky.




Thursday, November 17, 2011

prettier json

Yesterday I talked about JSON, and the inspect() method I use. While that example actually did some nice indenting, sometimes I have a mass of untabbed JSON I'd like to visually inspect. The best tool I've found for that is http://json.parser.online.fr/ . Slightly confusingly it shows both the "String parse" and the "JS eval" versions of the string, but usually it doesn't matter which one you look at. The way it builds a treeview of the code is really nice.

Before finding that page I used to just Google for "json pretty print" which would lead me to Cerny.js' entry as well as curiousconcept's. Both are ok in a pinch, I think the former sometimes got confused by special characters in the content, even if they were properly escaped.

Wednesday, November 16, 2011

loggin'

Yesterday I mentioned the importance of "log-based debugging". It's crucial to browser-based work, in part because alert()s and stepping through with the debugger mess up the timing of stuff, so they're not as much help for timing-related issues. I also think the act of putting in log statements forces a programmer to challenge their assumptions.

For reasons that are obscure to me, at work we call our main debug function "ccdebug". Its code is like this:

function ccdebug(s) {
  if (typeof console != "undefined" && typeof console.log != "undefined") {
    console.log(s);
  } 
}

Pretty simple! The check for console existing is necessary for preventing errors when the console isn't around...

I've been using that for just under 100% of my log statements... poking around I realize we have equivalents for console.warn() and console.error(). In firebug, the former has a nice yellow highlight, and the latter even includes a stack trace. So to improve my practice, I should probably start differentiating my information and coding messages from messages for more serious problems.

One other function I find useful, with both console.log() and good old alert():

function inspect(thing, indent){
if(indent == undefined || indent == true){
return JSON.stringify(thing, undefined," ");
}
return  JSON.stringify(thing);
}
That's just a great way to see the content of data structures and what not. The indent makes it a lot more readable, so I include it as the default.

Tuesday, November 15, 2011

simplicity simplicity simplicity -- shouldn't that just be 'simplicity'?

The other day I was thinking of Richard Gabriel's classic The Rise of 'Worse is Better'. The article has a kind of old context, but I think its core is still valid. (I also appreciate the vacillation within the article; these are issues about style and mood where there won't be a single correct answer.)

As the Wikipedia Page reiterates, the core components of "Worse is Better" are, in roughly descending order:
Simplicity
The design must be simple, both in implementation and interface. It is more important for the implementation to be simple than the interface. Simplicity is the most important consideration in a design.
Correctness
The design must be correct in all observable aspects. It is slightly better to be simple than correct.
Consistency
The design must not be overly inconsistent. Consistency can be sacrificed for simplicity in some cases, but it is better to drop those parts of the design that deal with less common circumstances than to introduce either complexity or inconsistency in the implementation.
Completeness
The design must cover as many important situations as is practical. All reasonably expected cases should be covered. Completeness can be sacrificed in favor of any other quality. In fact, completeness must be sacrificed whenever implementation simplicity is jeopardized. Consistency can be sacrificed to achieve completeness if simplicity is retained; especially worthless is consistency of interface.
The essay goes on to explain why these factors can be crucial to a technology really taking off. (Also it talks about the "New Jersey approach" vs the "MIT approach", terms I am including here for my future grepping needs.)

I find a rough analogy in my professional life as a UI Engineer when it comes to the selection of toolkits. I had a miserable time with "Wicket" and its bizarro blend of delicate flower Java class/HTML pairs. (It was barely ok for light work, but god help you in having to learn this whole lifecycle flow if something went wrong or you wanted to make your own component.) These days I've been arguing sticking with basic jQuery rather than taking on some heavier duty toolset like YUI or jsMVC.

So I ask myself, am I just a stick-in-the-mud curmudgeon who hates to learn new stuff? That's at least partially true: I'm much more interested in what technology can empower me to build than in the tools themselves, so I'm only interested in new toolsets when they let me do something new or in a vastly easier way, not just something old in a slightly more concise way. But I think there's something deeper in my preference for light weight toolkits, more profound...

I've said "People and computers should be judged by what they do, not by what (you think) they are." No one cares how finely crafted the objects in your code are, they just want to know, does it do the job well, and have you set yourself up to do the next few, slightly different jobs well. When I'm debugging, it's because the system is DOING something wrong, and I need to correct that behavior. My tools are-- lo and behold-- a debugger! and thoughtful logging... (good old log-based debugging is a crucial tool. I say that's because it forces you to think about what your preconceptions are at each step of the way, and then show them in action. But there's a chance it might also be because the debugging tools I used in college were so awful and opaque. Also, debuggers mess with the timing of stuff.)

Anyway, when I'm debugging, in a debugger, if I'm mostly looking at other's people code in the stacktrace, my job is much, much tougher. Most toolkits are extremely configuration heavy. (Toolkits by their nature don't just solve YOUR problem, but a hundred other problems as well, so you have to specify lots of things) It takes a fair amount of expertise and learning to set them up right, which costs time-- time you often don't have, the whole reason you're using the toolkit is for it to quickly solve your issue-- and when things break, there's often a huge gap between the misbehaving code and your error. The lighter the toolkit, the more likely the mistake is near where the debugger is showing the problem, the nearer the observed effect is from the code that caused it.

JQuery, I hardly ever have super tough to understand problems with. The few times the issue shows up in "jquery.min.js" itself, its been where I'm setting some property IE thinks should be read only or some such. Other tools I used, like Java RichFaces, the situation was much, much hairier. But with basic Javascript calling jQuery when needed, I can get to the problematic code easily.

Now this argument could be taken to an illogical extreme. I'm not saying you should code in assembly or anything like that... but your toolkits should be simple, reliable, and your widgets and libraries should be of the do one (hopefully difficult) thing and do it well.

(Of course, someone pointed out another reason to hate toolkits is they put a coating over the 90% of coding that is easy and pleasant and 'hey I built this!' and leave behind the 10% that is difficult anyway, and how you earn your pay... in fact they usually make that 10% significantly harder.)

Continuing the comparison to assembly, you still get people trying to spin Javascript as the Assembly language of the web, the code that all browsers speak, and it shows up in your debugger, but not what you want to be coding in. This kind of thinking is weak, because the additional layers, while slick and clever (epecially in the early baby tutorials) don't actually let you say stuff new. A concise essay about that in terms of toolkits is Uriel Katz' Why JavaScript is NOT the new Assembly  and a longer one against CoffeeScript and other pre-processor type languages is blog.izs.me's "JavaScript is Not Web Assembly".

Friday, November 11, 2011

not so angry birds

Today, our UX guy posted a link to Why Angry Birds is so successful and popular: a cognitive teardown of the user experience. This is the bulk of my resposne.

Cool article, though I disagree with what it assumes makes Angry Birds so popular.
The author is remiss in pointing out the obvious: some big chunk of Angry Bird’s addictiveness is because the base activity is a fun thing: it is fun and pleasant to launch a slingshot at a building of blocks.

At [Alleyoop, my College Readiness webcompany], we aren’t based on a core activity that offers such a low learning curve / high satisfaction + feedback . I think at the best points of [our Math practice and quiz subcomponent], kids can get that extra Zing! of satisfaction of a problem mastered, but in most other ways it’s a reach for us.

So with the article, I agree with some bits (the importance of pleasant and detailed visual design, even the inclusion of extra details like the chattering birds) and disagree with others (iPad icon spacing provoking a sense of tantalizing mystery? Puhleeze)

I thought margie's comment was more insightful to the charm of this particular game: (highlighting mine)
AB is a game for non-gamers. Gameplay is simple, the rewards are many and often, hence, continued play from all players. Any game that increases in difficulty and/or timing & speed too quickly I’ll drop out of […]. ~ AB is always the same: slingshot, birds, structures w/pigs.

I think the fact that players are frequently rewarded (it’s easy to pass a level, not so easy to 3 star a level) plays a huge part in why AB is so popular, especially with people who are not hardcore gamers.
Other commentators talk about “quick retrying ‘til I get it right” is a big aspect, maybe one we can learn from. Not punishing failure so much is a hallmark of modern gaming.

It’s funny too, the opening paragraphs:
Surprisingly, it is a rare client indeed who asks the opposing question: why is an interface so engaging that users cannot stop interacting with it?
The funny thing is, that’s not “engagement” so much as “low level addiction”. And frankly, popular games use some of the same pattern as drugs—an initial big rush (of success, in the case of games), a long haul of trying to recapture that high, and it being made harder to do so.

(It’s funny contrasting that with the addictiveness of say Farmville—there the addiction comes from a web of social obligations. The gameplay itself is decidedly NOT very fun in the way slingshots-at-buildings is, though it does carry a pleasant sense of “I Made This” construction. (I haven’t gotten into it either but I think Empires & Allies has those social and building aspects, along with an empowering “strong kid on the block” aspect in the fighting)

So I think [our company] would be well served if we could capture some of this addictiveness:
  • well balanced challenges with quick redo 
  • a carefully ramped increasing difficulty 
  • pleasant and juicy UI 
  • social obligations 
  • a sense of building 
The single biggest thing that Angry Birds and Farmville have that we don’t are a real feeling and visual model of steady progress. (With Angry Birds getting through a series of levels, with the chance to go back and do better, with Farmville a nicely expanded and built up farm.) [Our former point system is] now a currency. Badges were nice, but were always more of a novelty than a core “gotta catch ‘em all!” experience

BONUS:
Some more thoughts that were a bit too specific about Angry Birds as a game to be relevant to my company:
I think the article missed out one of the best UI bits for the "try again" factor: you get a little dotted line showing you what your last trajectory was, thus enabling a higher degree of fine tuning. This little dotted line is more significant than a lot of the things the article discusses.

Another thought I had: if I was designing Angry Birds, I might try to give it a split view: a zoomed-in view of the current bird (allowing more fine control of the trajectory at the launcher, and then a fun closeup view of the structure being destroyed, or possibly a pan back to the smug pigs if you totally miss) and then a view of the entire playfield, visible at all times. 

The thing is, I'm not sure if this system (more complex in its display, but simpler in its control scheme than panning and zooming Angry Birds) would be more or less satisfying than the current scheme. But when thinking about what deliberate choices Rovio made (vs, say, the delays once the bird has hit the building, which I think owes more to giving time to the physics engine to work things out than a deliberate design decision) alternative solutions to the challenges they faced should be discussed.

Wednesday, November 9, 2011

jsonp for cross-site fun

So, today's fun:
We run a few different servers for testing: www is our live site, cert is for final testing, test is for preliminary testing, and we hack DNS a bit so that dev loops back to each developer's machine.


We have a single WordPress install that we use for our blog, as well as to store the content for certain activities on the site. My most recent project was to add a simple tag system that would change a WP slug like 
[lookup value="user.profile.firstName"] 
into a rest call to /rest/user/profile and substitution with the fieldName parameter. (I also added conditional tags, something like 
[start_if value="user.grade" is="GRADE10"]Welcome to Tenth[end_if]
would display "Welcome to Tenth" only if the endpoint said that was their grade.


So when you just have the one WP install there's an obvious small problem when you want to test before pushing live, that while WP (which I keep accidentally calling "WordPerfect" not "WordPress", a habit that is catching on at work) can do its own preview, it's not part of the whole dev/test/cert/www cycle. We added a "src=http://dev.alleyoop.com" type parameter, telling the plugin where to pull its javascript guts and then rest calls from, but... d'ohh... the rest calls were failing, losing out to the draconian cross site scripting rules. 


The cool kids solution to this is JSONP, JSON-with-Padding. (The wikipedia page for it is a decent introduction.) The server needs to be configured to recongize a jsonp request, and then it forms a response of the form "<script>yourcallback(THE DATA)</script>"-- script tags aren't beholden to the usual xss rules. (Which is kind of a headscratcher, given that running code from another site seems to be a lot more dangerous than just grabbing data, but sometimes you have to take what you can get.)


So, in practice, I made a version of our wrapper for getting JSON that added a parameter dataType: "jsonp" to the jQuery.ajax call. We then ran smackdab into a kind of known Firefox issue (I'm not sure if us using a more up to date version of jQuery would have helped or not) where Firefox thinks that the JSON, what with its hashes and : and all, looks like it's trying to generate labels (what is this, BASIC?) and spits up "invalid label"... our fix for that was in the middle tier, a known solution is that wrapping the data in an additional set of parentheses fixes it, so that's what we did.


There's of course a bit of a security concern when you're allowing shenanigans like this-- especially if we were showing content from one user to another user. We'll look for some ways to tighten that up.

mobile flash in the pan

So the news is making the rounds, Adobe to stop doing mobile browser Flash.

For some Apple fans, this is a giant validation of Apple's view that Flash was the wrong technology for portable devices. (And as some have tweeted ActionScript might still be viable for making standalone apps.)

At work, our designer's response was "Aple wins!" and our lean startup guru marketing guy responded "The Internet wins!". That, along with Gruber's tweet thinking 2015 would mark the end of Desktop Flash players got me thinking...

What's next?

The most common opponent for Flash is usually described as "HTML5" which seems a little funny to me-- technically, HTML5 is about the semantics of markup, more of a topic for wonks than anyone else.

In practice, then It feels like there are two fronts for "not Flash", both powered by javascript. One is, and this is what I'm making my living with now, is what used to be called "DHTML"-- pages full of divs and graphics and one not, providing a faster and more interactive experience than the static pages of yore.

The other is stuff that makes heavy use of the "canvas" object. A lot of my gaming buddies are way into this as a technology. It's pretty cool, but there are two giant challenges for it to overcome to take the place of Flash: one is support for sound is still kind of iffy, you really have to dig if you want something that is very cross-browser and can provide "real time", synchronized sound effects. The other is support in IE (version 8 and earlier) tends to be lacking. (There are some libraries that use shims that do a good job of faking canvas support.)

I'm not sure what this means for me... Flash was on my "I should learn this" list, and now it's a little lower down.  (I took one 2 day intro class and it was frustrating because the class was geared at designers, and focused on the timeline, which STILL confuses me, as opposed to ActionScript, which felt very familiar when I helped a friend recode a few things.)

(UPDATE: Gruber also pointed to this CNET article that points out somethings Flash still does better than its alternatives...)

Tuesday, November 8, 2011

scope-a-dope

This is one of those posts that I'm a little nervous about writing, because I worry I might look a bit bad, since it represents a small bit of "trial and error" coding along with a slightly iffy theoretical understanding of the problem. Still, in the interest of being useful to my future self and maybe showing other people they're in the same boat, I'll put the process here.

I was trying to do a bit of caching of some data asynchronously.I had "neededEndpoints" that was a hash of the endpoints I needed to hit and store the data for in another hash, call it cache

So here was my first attempt: (it didn't look so blatantly wrong when I coded it, I've stripped out stuff in the name of simplicity)

for(var endpoint in neededEndpoints){
 jsonGet("/rest/"+endpoint, function(res){
                   cache[endpoint] = res;
             });
}

The trouble with this code is that javascript is not block scoped like some other C-like languages, and so "endpoint" is effectively passed by reference, not by value, and the last value of "endpoint" was used for all the cache storing.

I remembered in previous work we'd done here, we had a CreateDelegate function:
function CreateDelegate(scope, fn) {
    return function () {
    if(fn != undefined){
    fn.apply(scope, arguments);
    }
    };
}
Usually we'd call it with "this" as the argument for scope, but I wasn't getting the results I expected. Googling I found this page that gave me the nudge I needed to come up with this:
for(var endpoint in this.neededEndpoints){
 jsonGet("/rest/"+endpoint, 
               CreateDelegate({"ep":endpoint}, function(res){
cache[this.ep] = res;
   })
 );
}
So what's going on? The mental model I've come up with says CreateDelegate is in effect making a snapshot of the current state of things-- that's what a delegate is, in effect. It's actually the act of instantiation of CreateDelegate that makes the snapshot, and then the code inside it can have exactly the context we give it.


thoughts on keeping the global namespace clean

So one well known issue with javascript is that it's a bit too easy to pollute the global namespace.

Personally I find this is a big issue more in theory than in practice, choose reasonably distinct function and variable names, and you hardly ever have a problem.

Half the problem is that if you just start using a variable without a "var" declaration, it gets slapped into the global namespace. Douglas Crockford, among others, considers it a bit of misstep in the design of the language.

(The other half of the problem is the same "bootstrapping" problem any language faces: how do you tell the system where code execution starts, and where is the tree of object and functions rooted ? C and Java have their main(); in Javascript, you can start putting function declerations and even calls anywhere, in practice there's a lot of $(document).ready(function(){}); )

So, you can go a little crazy with loaders and tools to control your namespace and keep your private variables and functions private etc, and also with CreateDelegate() functions to pass thing to page elements and whatnot. This is overkill for most projects where you're more interested in the functioning of the site than making a reusable toolkit. (YMMV). A good compromise is "make one global variable per functional grouping". For example, today I was working on a "madlibs" controller (for eventual integration as a WordPress plugin) Part of the code for that was:
var ao_madlibs = new function(){
  this.neededEndpoints = {};
  this.doMadLibs = function(){
//CODE GOES HERE
    } //end doMadLibs
 }//end ao_madlibs


In practice I find this a good balance of control and ease of reading. One caveat, in the doMadLibs code I used jQuery's .each() function, and in the anonymous function in there, "this" had a different meaning, so I had to use the global reference ao_madlibs.


I was looking at a bit of coworkers' code... he's more of an architect, and cribbed this from FB's api code:

if (!window.AO) {
    window.AO = {
    processElements : function(){
                  //do something
        },

        someVariable: {}
   };
}
This code is using more of the associative array syntax, plus doing that check to make sure it's only called once. I find it's a little more "foreign" looking to me, but makes a good amount of sense if you're used to JS's variable syntax. Pick your poison I guess! Sometimes I do miss Java's class structure syntax...


The nice thing about using a global variable, to, is that you can really easily and concisely refer to your "functional grouping" in page elements and in other parts of your system, again without worrying about ever-changing meaning of "this" and using tons of oddball CreateDelegate functions... I find KISS (Keep it Simple Stupid) to be an important principle in making code I can read in the future, and in communicating my intent to other people looking at my code.

Monday, November 7, 2011

quick hit: a link o' snippets

http://www.catswhocode.com/blog/10-jquery-snippets-for-efficient-developers has some decent little snippets, I liked the age verification one in particular, and the one for seeing if an image had loaded was good as well.

Friday, November 4, 2011

metablogger meta blogger blogspot

So yesterday was the first day I tried making an embedded interactive bit... it wasn't as bad as I had feared (I've used other blogging software that has the WYSIWYG mode kind of running roughshod over the code you're trying to include), weirdly the one gotcha was that none of the parts seemed clickable... firedebug showed a "clickTrap" div around where I was expecting the action to be.  Doria's Design Notes had the fix, however, you need to put this as some CSS in the entry
<style>div.blogger-clickTrap {display: none;}</style>
Not sure what that's all about but the fix seems fine.

Thursday, November 3, 2011

a more pleasing easing

The other day I mentioned my admiration for making the jQuery animation default "swing". Today I'll talk about some of the other options provided by the jQuery Easing plugin.

Used judiciously, animations can make transitions to the state of the page less abrupt. Fiddling with easings gives you more options to add a "physicality" to the objects in question. Together, animation and easings can add a pleasant physicality (or bit of "juiciness" as I've got people saying at work.) to otherwise boring pages. (There's a reason why these kinds of animations and a sense of physicality is deeply baked into iOS...)

Actually, that page itself does a good job of showing usage... but I'm not crazy about the widget they give you to try out the various easings provided-- on that page, "The Clicker" always shows you 2 animations back to back (one for increasing the boxes size and one for putting it back) and so it's difficult to get a feel for each selection in isolation. Also, I think moving objects is a more common form of animation, and in general I prefer not to have to fiddle with select boxes. So I present: The Mover/Grower(tm). Like "The Clicker" it builds the list of easings by querying the module itself... you can set the speed, decide which (or both) of the things you want to animate, and then click to see any easing. (Click in rapid succession to combine.)

Mover:
Grower:

Speed: ms
Demonstrate: move grow both
jQuery Builtins: linear swing
From easing extension:

In terms of which of these to use, if you're in a hurry...our first use case for this was an object flying from off the screen-- "easeOutBounce" had the nicest feel to the landing.  Some of the "In" animations feel a little corny when they start, like a Hannah-Barbara cartoon character getting its feet under it before starting to run, but "easeInOutElastic" is subdued and pleasant.

Some other caveats are that animations can feel choppy if there are too many at once, or if the page is still kind of loading, or if there's a json-ish query or what have you, so want to be careful and minimize other things going on on the page when the thing loads (for example, a second delay before a message notifiation flies in, or launching a JSON request on animation completion, rather than at the same time as the animation started.)