Posts Tagged ‘javascript’

Thursday links (July 8)

Thursday, July 8th, 2010

Mobile

YouTube Mobile Gets a Kick Start
Battle of Champions: HTC Droid Incredible vs. Palm Pre Plus
Designing for the Retina Display (326ppi)
AUDIO: John Resig: You Don’t Know Mobile (Webstyle Magazine) – ~$5,000 minimum to do mobile testing
Tapworthy: Designing Great iPhone Apps
eMobile: We have the fastest network in Japan!
Apple iPad User Analysis — Phase II
VIDEO: Using iPhone with a Braille display (Victor Tsaran)
Mobile Access 2010 (Pew Research)
BlackBerry and iPhone losing ground to Android, overall smartphone growth (comScore data)

JavaScript

JavaScript needs modules!
JavaScript Cache Provider (Dustin Diaz)
Writing Testable JavaScript

CSS

VIDEO: Nicole Sullivan on CSS (The Big Web Show)
CSS Media Queries & Using Available Space
Data URIs make CSS sprites obsolete (Nicholas Zakas)

Books

HTML5 For Web Designers
Tapworthy: Designing Great iPhone Apps
HTML5: Up and Running
JavaScript Patterns

Etc.

Web Forms: Semantic Mark Up in our Forms [part 2]
Non Hover – “Elements that rely only on mousemove, mouseover, mouseout or the CSS pseudo-class :hover may not always behave as expected on a touch-screen device such as iPad or iPhone.”
Video to ASCII conversion with Canvas
CAPTCHA slider
Rich snippets and structured markup (Google Webmaster Central) (SEO)
Firefox 4 beta 1 is here – what’s in it for web developers?

Using mobile-specific HTML, CSS, and JavaScript (Mobile web part 5)

Tuesday, June 29th, 2010

Mobile-specific HTML

Use the viewport tag to properly fit the content to the screen:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

Use the tel scheme for telephone numbers, allowing users to initiate calls by clicking:

<a href="tel:18005555555">Call us at 1-800-555-5555</a>

Or use the sms scheme to initiate an SMS message:

<a href="sms:18005555555">
<a href="sms:18005555555,18005555556">          <!-- multiple recipients -->
<a href="sms:18005555555?body=Text+goes+here">  <!-- predefined message body -->

You also have access to several Apple-specific tags to use in your web application (iPhone and iPod Touch):

// iOS 1.1.3+: this is the icon that's used when the user adds your app to the home screen
<link rel="apple-touch-icon" href="/custom_icon.png"/>

// iOS 3+: full-screen startup splash screen image
<link rel="apple-touch-startup-image" href="/startup.png">

// enable full-screen mode
<meta name="apple-mobile-web-app-capable" content="yes" />

// controls the appearance of the status bar in full-screen mode
<meta name="apple-mobile-web-app-status-bar-style" content="black" />

And also some handy attributes to turn off annoying autocorrect features (works on iPhone, but anything else?):

<input autocorrect="off" autocomplete="off" autocapitalize="off">

Mobile-specific CSS

Media queries enable you to target specific features (screen width, orientation, resolution) within CSS itself. You can use them two ways: 1) inline in a CSS stylesheet or 2) as the “media” attribute in the link tag, which targets an external stylesheet. The following is an example of inline CSS that’s applied only when the device is in portrait mode:

@media all and (orientation: portrait) {
	body { }
	div { }
}

Here’s the same media query using the other method, which points to an external stylesheet (not recommended, as it creates another network request):

<link rel="stylesheet" media="all and (orientation: portrait)" href="portrait.css" />

Here’s a few examples:

// target mobile devices
@media only screen and (max-device-width: 480px) {
	body { max-width: 100%; }
}

// recent Webkit-specific media query to target the iPhone 4's high-resolution Retina display
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
	// CSS goes here
}

// should technically achieve a similar result to the above query,
// targeting based on screen resolution (the iPhone 4 has 326 ppi/dpi)
@media only screen and (min-resolution: 300dpi) {
	// CSS goes here
}

Read more: Media queries (Mozilla Developer Center)

Mobile-specific JavaScript

window.navigator.onLine (boolean): not strictly mobile, but helpful for apps to determine if they’re being run offline

window.navigator.standalone (boolean, iOS 2.1+): determine if it’s running in full-screen mode (Apple only?)

touch events (iOS, Android 2.2+): touchstart, touchmove, touchend, touchcancel

gesture events (Apple only, iOS 2+): gesturestart, gesturechange, gesturend give access to predefined gestures (rotation, scale, position)

orientationchange event: triggered every 90 degrees of rotation (portrait and landscape modes)

MozOrientation (Fennec/Firefox Mobile, Firefox 3.5+): also not strictly mobile. Gives access to the device’s accelerometer (x-y-z orientation data), updated periodically. Works on Android phones (I tested on the Nexus One), Windows Mobile, etc. On the desktop this works with laptops such as Thinkpads and MacBooks.

-near future: camera/microphone access in Android 2.3 (announced at Google I/O 2010) through the Capture API

If you’re developing for a BlackBerry Widget, you have access to proprietary information through the blackberry object (which gives access to useful information such as blackberry.network [returns values such as CDMA and Wi-Fi] and blackberry.system).

You also have the option to use PhoneGap, which augments JavaScript and gives you access to more phone features that native apps would have access to.

Use a mobile-optimized JavaScript library

Because smartphone browsers are standards-based, the aim of a JavaScript library on mobile is less towards API normalization and more towards providing an actual UI framework, usually to emulate the feel of native apps (and to provide easier workarounds to lack of access to position:fixed). We’ve seen a few libraries released that emulate the iPhone UI, and in the future we might see libraries emulating the Android UI, as well as entirely new UIs.

There’s also a bit to be said about simply loading full desktop JavaScript libraries into mobile clients. In my opinion this doesn’t particularly make sense, especially in a world where latency and bandwidth are so much more of a concern. It doesn’t make sense to force the user wait longer and download code that’s ultimately useless to them (hacks for desktop browsers such as IE 6, etc).

Here’s a few of the mobile libraries now available:
-Sencha Touch
-baseJS
-XUI
-jQTouch: jQuery-style mobile library that emulates the look of the iPhone UI
-iUI: the first JavaScript library to be released, emulates the look of the iPhone UI. Originally coded by Joe Hewitt.
-PastryKit: Apple proprietary non-public JavaScript library with no available documentation

Take advantage of new stuff!

While not specific to mobile, there’s a lot of new stuff in general that you can use. If you limit yourself to the top smartphones (iPhone, Android, and maybe webOS), compared to the desktop you immediately have access to an even wider array of new stuff, especially many Webkit proprietary features, since most of these top smartphones have browsers based on Webkit.

-HTML: new tags (HTML5 (I’m sure you’ve heard of it by now…))
-CSS: 2d transforms, 3d transforms, animation, border radius, custom fonts with @font-face, etc.
-JavaScript: strict mode, constants, block scope, Date.now(), etc.

Related posts

This post is part of a series on the mobile web. You can read the other parts of the series here:
Part 1: The viewport metatag
Part 2: The mobile developer’s toolkit
Part 3: Designing buttons that don’t suck
Part 4: On designing a mobile webpage

JavaScript SunSpider: HTC Evo versus HTC Incredible versus Nexus One

Thursday, June 10th, 2010

Result table

Test Evo (2.1) Incredible (2.1) Nexus One (2.2)
Total 16167ms 15237ms 5452ms
3D 2014ms 1835ms 946ms
Access 2126ms 1892ms 463ms
Bitops 1519ms 1591ms 360ms
Controlflow 243ms 206ms 20ms
Crypto 1033ms 1003ms 344ms
Date 1849ms 1896ms 639ms
Math 1684ms 1419ms 602ms
Regexp 1779ms 1673ms 155ms
String 3920ms 3722ms 1923ms

Thoughts

The Incredible is just slightly faster than the Evo, to the point where it’s probably negligible or within a margin of error. Both of these phones run on Android 2.1 with HTC’s Sense UI modifications, and represent the latest and greatest in Android phones available on the market today. Both run on the same 1GHz Snapdragon processor (QSD8650). The Nexus One is a bit older, and runs with an older version of the Snapdragon processor (QSD8250), however it still runs at 1GHz just like the other two phones.

As you can see the Nexus One blows away all the competition because it’s running Android 2.2 Froyo. These results were quite a shock to me and are quite impressive. These results even blow away Apple’s new iOS 4 running on my iPhone 3GS, which clocked in at a total time of 13787ms compared to the Nexus One’s startling 5452ms.

Testing methodology

Test: SunSpider 0.9.1

Devices: HTC Evo (Android 2.1), HTC Incredible (Android 2.1), HTC Nexus One (Android 2.2)

The SunSpider test was run five times on each phone. The phone was completely turned off and on before each test. The most extreme values of the five tests were thrown out, and the resulting four tests were averaged (sometimes from three tests when the values were very close together).

Raw results:

SunSpider HTC Evo results (5 tests)

SunSpider HTC Incredible results (5 tests)

SunSpider HTC Nexus One results (5 tests)

Related links

JavaScript SunSpider test: iOS 3.1.3 versus iOS 4 GM

Video: John Resig – Testing, Performance Analysis, and jQuery 1.4

Monday, December 21st, 2009

In case you hadn’t seen it yet, John Resig was kind enough to stop by Yahoo! for the December Bayjax meetup. Here’s the video:

Usually developers are more interested in just getting the dang code to work, and as a result actual the testing and maintenance of JavaScript isn’t talked about too much, so I’m sure this will be new territory for many developers. And since it’s John Resig speaking, there was of course a bit about using TestSwarm, a testing distributed framework-agnostic automated testing tool (that’s a mouthful!).

Included in the talk are good things to note while testing, such as the fact unless you’re running Firefox or Chrome on Windows, all test times have a margin of error of up to 15ms (not to be confused with PPK’s observation of the delay between JavaScript computation and browser rendering).

(via YUIBlog)

JavaScript tidbit: special variables ($, $$, _, etc)

Tuesday, December 8th, 2009

You’re probably used to typical variables names such as the following:

var personName = 'Joe';

You may not realize it, but there are some non-alphanumeric variables at your disposal.

Using $

For instance, the $ variable has been made popular by several JavaScript libraries, most notably jQuery. You can use it to alias operations that are commonly performed, such as the following (1):

var $ = document.getElementById;
var myElement = $('targetElement');

If you declare this variable outside of a function it will be a global variable and will compete with libraries that use the same global variable, so it’s probably best not to use it.

Interestingly, originally the dollar sign $ was originally intended for “mechanically generated code” (2), but as the usage of the symbol has become popular for other purposes, it looks like the latest version of JavaScript (ECMAScript 5th edition) now officially “oks” its use:

This standard specifies specific character additions: The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

Using $$

Some have come up with the solution of simply using two or more $$ symbols in order to distinguish the variable from libraries that just use a single $:

var $$ = document.getElementById;
var myElement = $$('targetElement');

Using _

You will find that you can use the underscore _ in the same way to alias variables and functions:

var _ = document.getElementById;
var myElement = _('targetElement');

Other symbols

If you’re really getting adventurous, you can even try using other symbols such as square root √, which seems to work just fine, just as $ and _ above. The only problem: it’s quite inconvenient using it, since it’s not available on any keyboards (except through some crazy key combinations perhaps).

Or you can put the symbol to use doing what you would naturally think it should do…

var √ = Math.sqrt;
alert(√(4));   // 2

References

(1) Even Faster Web Sites, p. 128
(2) Stackoverflow: Why would a javascript variable start with a dollar sign?

Ways of passing data to functions in JavaScript

Friday, December 4th, 2009

Passing data is quite important in functional programming languages like JavaScript. When there are multiple functions (which is most of the time), there needs to be a way to pass data between the functions. This is done by passing values in parenthesis: myFunction(myData). Even when there is no data to be passed, we still have to declare and execute functions by using parenthesis: myFunction().

Simple Passing

I’ve already referred to the common method of passing data. Here’s an example of the code in action:

function greeting (name) {
    alert('Hello ' + name);
}
var personsName = 'Joe';
greeting(personsName);  // Hello Joe

This example only passes one variable to the function. Note that we can get rid of the variable personsName and make the string on the fly. So the code above is equivalent to this:

function greeting (name) {
    alert('Hello ' + name);
}
greeting('Joe');  // Hello Joe

Ok. Now let’s suppose we have a function that accepts two variables:

function greeting (firstName, lastName) {
    alert('Hello ' + firstName + ' ' + lastName);
}
greeting('Joe', 'Schmoe');  // Hello Joe Schmoe

This doesn’t look too hard. But there’s a catch – the person writing the code has to remember the order of variables to pass in. Suppose they call the function like this:

function greeting (firstName, lastName) {
    alert('Hello ' + firstName + ' ' + lastName);
}
greeting('Schmoe', 'Joe');  // Hello Schmoe Joe

That’s no good! This isn’t the result we want. In the case of firstName and lastName the variable order isn’t too hard to remember, but in other cases the variables aren’t in any logical order, which can cause confusion.

No constructor overloading

Unlike other languages such as C++ and Java, JavaScript has no constructor overloading. In fact, JavaScript is (for better or worse) not even strict about enforcing the number of variables passed in. For example, the following code works fine and throws no errors, even though we’re not passing in a variable in the function call:

function test (someVar) {
    // do stuff
};
test();  // no errors!

It’s only when you try to use someVar within the function that causes the problems. Otherwise, everything’s working just fine and dandy.

What happens if we try the other case scenario: pass in more variables than the function expects? No errors again:

function test () {
    // do stuff
};
test('testing 123');  // again, no errors

And what happens if we try to declare a function with the same name? No errors, but the previous function is overwritten (this is generally to be avoided of course):

function test () {
    alert('First function');
};
function test () {
    alert('Second function');
};
test();  // Second function

Because JavaScript has no function overloading, all it takes to overwrite another function is to redeclare a function with the same name. It doesn’t matter what sort of arguments they accept.

Passing with the help of the arguments object

As it turns out, JavaScript has a handy arguments object to access the arguments passed into each function:

function test () {
    alert(arguments[0]);    // testing 123
};
test('testing 123');

In the above case the arguments object acts just as an array – it’s 0-indexed and can be used to access any arbitrary number of arguments. But arguments also has an interesting and useful property: length. Using arguments.length, we can traverse the array of arguments. This is handy in cases where we might want to add an arbitrary number of elements together:

function add () {
    var sumTotal = 0;                        // initialize total to 0

    for(var i=0; i<arguments.length; i++) {  // for each argument
        sumTotal += arguments[i];            // add current argument to total
    }

    alert(sumTotal);
};
add(2, 3, 4);  // 9
add(1, 1, 1, 1, 1, 1, 1, 1, 1);  // 9

Passing an object

JavaScript libraries such as YUI have already learned that the variable order is a common nuisance and an opportunity to introduce errors, so they’ve come up with a solution: pass a single object to the function. It ends up looking something like this:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
var nameObject = {};
nameObject.first = 'Joe';
nameObject.last = 'Schmoe';
greeting(nameObject);  // Hello Joe Schmoe

Now the variables become properties of a single object which is passed into the function. And it doesn’t matter which order the properties are declared in, which is a great relief to the developer.

Note that we can simplify the above code:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
var nameObject = {
    first: 'Joe',
    last: 'Schmoe'
};
greeting(nameObject);  // Hello Joe Schmoe

And we can simplify even further:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
greeting({
    first: 'Joe',
    last: 'Schmoe'
});  // Hello Joe Schmoe

This is the form commonly used in these JavaScript libraries. It’s easy to copy-and-paste example code, but it might not always be so obvious what’s going on behind the scenes. You can see that just as we bypassed declaring a named variable in the Simple Passing model (with greeting(”)), here we use the same shortcut and bypass declaring a named object (with greeting({})).

call() and apply()

These two methods have different techniques for passing data to functions, but I’m going to have to hold off on them for now. It’s a bit complicated, since they’re only used to execute methods (functions) in other object contexts. But seeing as I need to explain object context to get into that, I’ll save that for a future entry!

Pitfalls of declaring variables in JavaScript

Wednesday, November 18th, 2009

Introduction

One of the things that’s always been confusing to me is that there are multiple ways to declare variables in JavaScript, and some ways are better than others. For the beginner programmer, just getting to code to work means complete success, but for the intermediate or advanced programmer, this is just the first step. The next step is to clean up the code and make sure everything is written in the best way it could have been written.

Declaring variables seems like such a basic thing that one almost feels insulted reading about it. Yes, this whole post is about declaring variables. But not just this – it’s about declaring variables the right way. This means declaring variables in the scope they were intended to be declared in.  For the most part this means writing variables in the scope of a function, as opposed to the global namespace (in which everything becomes a property of the window object).

Global variables can be declared in functions

When I was starting to learn JavaScript, I read about global and functional scope and wrongly assumed that functions completely protected the variables declared inside.  As it turns out, there’s many ways to create global variables in JavaScript, and none of them throw up red flags or sound off bells and whistles (unfortunately).

Here’s a few ways to create global variables in JavaScript:

// Creating global variables outside of a function
window.global1 = 1;
global2 = 2;
var global3 = 3;

// Created global variables within a function
function test() {
    global4 = 4;
    window.global5 = 5;
};
test();

You can confirm this for yourself by checking the values of the variables with alert().

Good practice: always precede variables with var

What I learned was that it was essentially good practice to always write variables preceded by the var keyword.  For variables declared outside of functions this has no effect – they are still global, but for variables within functions this ensures that they’re kept within their functional scope:

var global = null;
function test() {
    var local = null;
}
test();

Same name, but different variables

And check this out – confusingly, you can create a global variable, then create a variable with the same name that’s functionally-scoped, yet a completely different variable!

var number = 0;

function test() {
    var number = 1;
}
test();

alert(number);  // 0

When you precede a variable with the var keyword, you’re essentially saying you’re creating the variable for the first time.  So when you create “number” inside the function, no error is thrown because the variable is created in the function’s scope.  If you try to create another variable with the name “number” inside the function, you will get an error because it’s already been defined within the scope.

There’s no such thing as magical protective parenthesis

For some reason I was further mistaken into believing that extra parenthesis around an anonymous function magically protected the variables within:

(function() {
    global = null;
    var local = null;
})();

Nope – as you can see, the global variable is still global since it’s not preceded by the var keyword.  All the extra parenthesis do is execute the function immediately.  That’s it.

Shorthand for declaring multiple functionally-scoped variables

The following code ensures each variable is functionally (locally) scoped, even though only the first variable is preceded by the var keyword:

function test() {
    var local1 = null,
        local2 = null;
}
test();

Multiple variable declaration equivalence gives different scope to each variable

Today I learned another way to mistakenly create a global variable.  Trying to be fancy and declare multiple variables to be the same value, I mistakenly created a global variable (again, no bells and whistles went off to warn me, unfortunately):

function test() {
    var local = global = null;
}
test();

This sets both variables to “null” using the shortest code possible, but unfortunately only the variable “local” is preceded by the var keyword, so only that variable will be in its proper functional scope. Variable “global”, on the other hand, is… well… global. (thanks to Crescent Fish)

You learn something new every day…

Update 1

If you want to check your code for “accidental global variables” you can use JSLint or you can even use Firebug (click on the Script tab, then click on “New watch expression…”, then type “window”, which will display all the properties of the window object – these are all global variables!). Thanks to Nick for the Firebug tip.

Update 2

Just another quick note to remind you that after a variable has been initially declared, the scope will not change. Which is why you can redefine variables, but have them keep their scope:

function test() {
    var local = null;
    local = 5;    // still keeps its local/functional scope
}
test();

As you can see above, the variable “local” keeps its local scope, even though it’s redefined to be 5. This is one of the reasons it’s recommended to declare all variables at the start of a function – to make sure the scope gets set correctly.

One final note: var should only be used when declaring a variable for the first time. If you try to use var for the same variable name in the same scope, it will result in an error:

function test() {
    var local = null;
    var local = 5;    // throws an error!
}
test();

Update 3: Graphical representation

Scope in JavaScript

Scope in JavaScript

JavaScript Tidbit: Block scope with “let”

Tuesday, September 15th, 2009

JavaScript has functional scope. Meaning that if you (properly) define variables within functions, those variables remain accessible only inside the function.

Block scope, on the other hand, defines scope within a block of code, usually defined by braces. JavaScript now has block scope as of version 1.7, which means it’s available in these browsers:

  • Firefox 2+

Block scope is enabled in JavaScript with the use of “let”:

let(x=100) {
    alert(x);
};

It also works perfectly well on one line, without the use of braces:

let(x=100) alert(x);

Note that we can define global variables with the same name outside the block scope and the variables won’t interfere with each other:

x = 200;
let(x=100) alert(x);
alert(x);
// result: 100, 200

Note that there’s a slight caveat – not only is this not available in any version of IE, but it also requires a special script type declaration in order to work (at least for Firefox): type=”text/javascript;version=1.7″

References:
JavaScript Versions
Video: Best Practices in Javascript Library Design (John Resig)
New in JavaScript 1.7

JavaScript Tidbit: Shorthand Object Instantiation

Monday, September 14th, 2009

The skinny: here’s a neat little trick to reduce the amount of code users have to type to instantiate objects:

function jQuery(str, con){
    if ( window == this )
        return new jQuery(str, con);
    // ...
}

new jQuery("#foo"); // this is now equivalent...
jQuery("#foo");     // ...to this!

Explanation: when jQuery(“#foo”) is typed, the function first determines if the context in which it’s being called is the global object (window).  If it is, it returns an instantiation of itself.  When it’s instantiated, the context in which it’s being called is inside its own function, and NOT within the global object (window), thus it bypasses our little instantiation trick and moves on to execute any remaining code in the function.

From John Resig’s Best Practices in Javascript Library Design