Category Archives: Javascript

FB.login doesn’t work on Google Chrome–Facebook doesn’t seem to care

If your web application’s login mechanism integrates with Facebook’s Login functionality, and if you’re using the latest Javascript SDK from Facebook, you might have noticed that users cannot login if you use the FB.login() Javascript function. This issue’s been there for quite some time now, although I only came across it a few weeks back when I updated PosterMyWall’s Facebook integration (from the legacy ‘REST’ API to the latest graph based API).

So far I haven’t gotten any response from Facebook as to when they’ll get around to fixing this critical issue. I’ve created a question over at Stackoverflow; FB.login dialog does not close on Google Chrome. If you have any non-hacky work-arounds, please respond over at Stackoverflow. Also, be sure to vote-up the Facebook bugzilla ticket linked to in the question.

Advertisements

Firefox 3 performance numbers – impressive

Stumbled upon these Firefox 3 Javascript performance numbers. Firefox 3 preBeta 4 is about 3.6x times faster than Firefox 2.0.0.12 and a huge 7.5x times faster than IE 7 at crunching Javascript.

I’ve always been pretty impressed by Safari’s js performance, but looks like FF 3 is going to take things to a whole new level.

Tagged

Games in Javascript – Pointless

I came across a Javascript Game Library some time back, while I myself was working on a cross-browser graphics library, trying to make the canvas tag work the same across all browsers. (Btw, Explorer Canvas is great to have when making your canvas code run on IE6. It’s still not ready for production sites though, as the performance on IE6 is pretty abysmal, but it’s still a nice thing to have)

Coming back to the game library, I find it completely pointless. It would have been great to have something like this a decade back maybe, when Flash wasn’t as widely available as it is now. I gave some of these Javascript games a whirl, but most didn’t run on Firefox, and those that did run on IE6 had atrocious ‘graphics’. Why would you go through the pain of wandering through the maze of cross browser issues and wrestling with the obvious lack of any graphical power in Javascript and try to make a game in it, when you can just make a better looking one in Flash or Silverlight?

I’m a huge Javascript nut, but I know its limitations. Game graphics isn’t what Javascript was designed to do. Although many apps on the web these days are pushing the limits of browsers and Javascript, enjoyable games in a native browser environment are still a long way off.

Tagged

Recent Reading – Usability and Rhinos

Read two blog posts yesterday that I thought I’d mention.

Code’s Worst Enemy (Stevey’s Blog Rants): A monster of a rant (5222 words!), mainly talking about Java code’s natural tendency to be bloated and that programmers should strive for brevity of code. Apparently Steve’s been coding a game in Java for a hobby, and the code base got huge and unmanageable. Now he’s thinking of converting the game to Rhino (Javascript running on the JVM) partly because of Javascript’s immense expressive power, something that I’ve been ranting about for quite some time now. Can’t wait for Rhino on Rails!

Bootstrap Design for Geek Powered Startups: Not a regular reader of Tony’s … stumbled on the post from del.icio.us. He’s basically highlighting factors to think about when making your own startup. Although everything that he highlights is true, two of his suggestion

“a UI designer should be baked into your organization as early as possible”

and

“usability testing should be baked into your organization from day one” 

are really important because startups usually don’t pay much attention to them.

Although I think UI designers are very rare in Pakistan, I still think that in house training can go a long way in making a ‘graphics designer’ into a ‘Web UI designer’. First of course, we have to get rid of the misconception that both are one and the same, a belief that’s practically ubiquitous in Pakistan.

Sadly, I don’t see Usability Testing happening anytime soon in our industry. If there’s any ISV or startup out there that does work in Usability, and you’re in Pakistan, speak up!

Tagged

iUI – easier iPhone app development

Joe Hewitt, the guy who brought us the awesome Firebug now introduces iUI, which is supposed to make writing applications for the iPhone easier (get your sample apps here). It’s not really a Javascript library right now. It’s more like a set of design elements and methods that will help an iPhone developer. I’m sure we’ll see more bells and whistles added to it over time.

I’m surprised though that Apple hasn’t come out with similar utilities (or at least detailed example apps) for their iPhone developer community. (btw, Aptana rolled out their iPhone plugin recently, so if you’re looking for an iPhone IDE, look no further)

Not sure if anyone in Pakistan is working on any iPhone apps yet. I guess none of the local sites are in any hurry, because we probably won’t be seeing any iPhones in Pakistan anytime soon (but it will be super cool to see iPhone versions of say, Rozee).

But anyways, I don’t think this makes me crave an iPhone as badly as I once did (and I’m a total Apple nut case).

Writing better Javascript – The Essentials

When I came across Javascript for the first time, it was in the form of a snippet that I put on a page to do some validation. Most web developers start out with Javascript in the same way. Do a little validation here, a rollover effect there , trivial stuff like that. That gets most people started with Javascript on the wrong foot, thinking that it’s a mere scripting aid.

With more and more Javascript code being released on the web, and with more applications relying on Ajax and Javascript effects in a bid to jump onto the Web 2.0 bandwagon, it is really important that people starting out with Javascript are aware of its strengths, weaknesses and quirks before they actually write production code.

So here’s my attempt at making the lives of Javascript beginners a little easier.

Know the Language
Before you can actually write quality code in a language, you have to know it inside out. Fortunately, Javascript is not a huge language to cover. It is hover, very versatile. The expressive power that you have at your disposal when you’re coding in Javascript is amazing. I can ramble on endlessly about how awesome Javascript is, so I’ll get right to the point. The best reference IMO that’ll get you started in the right direction is this 3 part series of lectures by Douglas Crockford. He’s currently a Senior Javascript Architect at Yahoo!, and his lectures are very nicely organized and his delivery style keeps you interested. Also, if you’re interested in the history of the language and the browser wars that played a great part in shaping how we code for the Web today, you’ll love these lectures. Even after sitting through these lectures, I still use the power point slides for quick reference whenever I’m unsure about something.
Sit through these lectures with the intent of learning something and by the time you finish, not only will you be crazy excited about Javascript, you’ll have a solid foundation to begin writing code and building on what you’ve learnt. For me, these lectures have defined how I write Javascript code. The difference between the code I wrote before and after these lectures is staggering. So if you don’t know why you should use === and !== instead of == and !=, or what a lambda or closure is, or how to do prototypal inheritance, I suggest you click here.

Unobtrusive Javascript
If you’re into the whole separation of behavior, content and presentation on the web thing then you’ll know what I’m talking about. If you don’t know what the previous sentence meant, you need to crawl out from your hiding place under a rock. There are many schools of thought on unobtrusive Javascript. I being a firm believer in KISS (Keep It Simple Stupid) have a don’t overdo it approach to unobtrusive Javascript. If it’s helping me out, fine, if a certain thing is too hard to code without having Javascript in the HTML, so be it. Please forgive me my unobtrusive fanatic friends.
So what you basically need to do is write all your Javascript code in a separate .js file. There are many advantages to this technique.

  • All your Javascript is cached in one go, leaving only the HTML to be fetched from the server on each page. (This depends on how you’ve organized your .js files)
  • Code reusability.
  • Easier to organize your code in packages/classes. You can write a controller for each page that will initialize its Javascript components, or better yet, have a base controller which initializes common components and all other controllers inherit from the base controller.
  • Improvement in code readability, no more HTML strewn with Javascript.

Time to write some code. So say that you have an image that has a rollover effect. If you had been coding 5 years ago, you would have done something like this:
<img src="button.gif" onmouseover="this.src='button_over.gif'" onmouseout="this.src='button.gif'" alt="" />

Say you have twenty such buttons all over the page, you’d have to do this to each one of them. Here’s how to do it the unobtrusive way (simplified code):
HTML
<img src="button.gif" class="rollover" alt="" />
Javascript
function activateRollovers(){
var rollovers = document.getElementsByClassName('rollover');
for(var i=0;i<rollovers.lenght;i++){
rollovers[i].onmouseover = function(){
// insert '_over' in image name before image extension
};
rollovers[i].onmouseout = function(){
// remove '_over' in image name before image extension
}
}
}
// call this function when window loads (prototype.js method)
Event.observe(window, 'load', activateRollovers);

CSS class names are most commonly used for the purpose of grabbing elements of a certain type, but there are other methods as well, described in this example of unobtrusive form validation.

Objects and Functions
Everything is an object in Javascript. A function is an object. You can even define a function as a variable. What makes Javascript objects truly unique is that they are essentially Hashmaps. Objects are comprised of name <-> value pairs, where the name is a string and the value is an object. Master the functional aspects of Javascript (functions as variables & objects, passing functions, function pointers), and you’ll be on you’re on your way to Javascript greatness.

Frameworks and Libraries
It is pretty well known that there is no dearth of Javascript frameworks and libraries. The web is overflowing with them. Choosing the right on for your project is the important bit.
But why use a framework at all you say? Javascript has its share of quirks and flaws. And inconsistent implementation and incompatible APIs by browsers doesn’t help either. The extensible nature of Javascript (you can modify built in objects via their prototypes) allows frameworks to provide richer built in objects and cross browser compatible methods. Most frameworks provide Ajax objects, which allow easy communication with the server.
I’ve personally always used the prototype framework. Yahoo!’s YUI has a rich set of UI controls, and is a good choice if your site has heavy Javascript/Ajax UI work. jQuery, mootools and dojo all come highly recommended. Read through Justin’s Top 5 Javascript frameworks list to get a clearer view of the playing field. Although I disagree with his ranking, I found the comments to the post enlightening.

Ajax Patterns
Ajax IMO is a necessary evil. I’d rather work in Flex, or maybe even Silverlight for RIA. (Can’t wait for JavaFX!) But as long as there’s a demand for DHTML, you’re going to have to write Ajax code. There are a gzillion different ways of doing a thing using Ajax, so I highly recommend using Ajax Patterns as a reference for all your Ajax design and coding time decisions. If you’re going to do something wrong, do it right.

Exception Handling
As I’m writing this post on the Posts page in WordPress, Firebug is alerting me to a Javascript error on this page. The web has more Javascript errors than it actually has web pages. Probably. My point is that exception handling is rarely applied in Javascript code on web pages. The fact that Javascript is loosely typed is probably one of the main reasons why programmers get sloppy and don’t feel that their Javascript code needs as much exception handling as their Java/.NET code.
Javascript exceptions in the worst case can render unusable UI on a web page. Using exception handling will allow you to show something like an error message or report bug form in place of the UI, instead of something broken. Or maybe even switch to a non-Javascript UI on an exception. The sky’s the limit.

I hope this rant has set you off on the right foot with Javascript. Treat your Javascript code as more than a code snippet, and your code will be significantly more robust, efficient and manageable.

Standards Compliant Web Development Starter

With browsers paying more attention to web standards, and W3C working towards more mature ones, now is a great time for developers to embrace these standards, and make their lives easier.

So what does it take to ditch your table layouts, inline styles, deprecated HTML tags and rampant Javascript snippets? LOTS of reading, LOTS of patience and a shoulder to cry on. Commitment to code quality and standards doesn’t hurt either, but more on that later.

So to make this journey of the everyday web developer easier, here’s a linkfest of references scattered across the web that will (should =p) help in getting up to speed with the latest web standard compliant coding techniques.

To get in the mood, it’ll help to read 12 Lessons for Those Afraid of CSS and Standards first.

Separation of Content and Presentation

XHTML
Basics

Layout (Floating & Positioning, CSS Columns and Tableless Forms)
Basically you’ll be using <div> for layout and positioning of content, <span> for formatting different looking text, <ul>, <ol> & <li> for ordered items (lists) and <fieldset>, <label> & <input> for your form elements.

CSS

Javascript (a little bit of Ajax as well)
Basically you’d want to have your Javascript separated from your XHTML, it’s called Unobtrusive Javascript if you like buzzwords. Benefits include code reuse, better OO design, less loading time for pages etc.

CheatSheets!

Sites to follow
Before turning to Google for your searching needs, consult these sites.

When coding for the web, it is important to strike a balance between standards and practicality. It may take you twice as long to code something which is standards compliant, then something you can cook together while bending the standards. Differences in the 4 major browsers (IE, FF, Safari & Opera) also won’t make you life any easier.

Be sure to comment any links that you think are useful!!

Images with border effects and onclick – IE problem

These days I’m working on an Ajax driven photo customization UI where the user can select from a range of frames that they can put on the photo. In the middle of the page is their photo, and in the right corner there’s a scrollable table with frames (2 in each row).

Everything’s hunky dory until I decide to add a border effect on frame images, so that on mouseover (or hover in CSS) the border increases (pretty standard stuff). I go ahead and add the following in the stylesheet and code respectively:

CSS:
img.frame {
border:#80A7D2;
border-width:1px;
border-style:solid;
margin:3px;
}
img.frame:hover {
border:width:2px;
margin:2px;
}

HTML:
<img class="frame" src="foo" alt="bar" onclick="doStuff()"/>

Problem
This gives me a nice border effect and the onclick of the <img> works as expected in FireFox. But when I verify this in IE, there’s no border effect whatsoever.

Solution Part 1
So I look at some legacy code elsewhere in the application, because there are areas in which this border effect is being used (albeit slightly differently), and what results is an encapsulation of the <img> tag with an <a> tag. The style is also changed to apply it to the anchor instead of the image:

CSS:
a.frame_holder {
border:#80A7D2;
border-width:1px;
border-style:solid;
margin:3px;
display:block;
}
a.frame_holder:hover {
border:width:2px;
margin:2px;
display:block;
}

HTML:
<a class="frame_holder" href="#"><img src="foo" alt="bar" onclick="doStuff()"/></a>

The border effect doesn’t work unless you set the display type to ‘block’. Another problem is the href=”#” which scrolls the page to the top if you click the link. Now that’s perfectly acceptable if you’re going to another page on clicking the link, since the scrolling never happens. But while using Ajax, you don’t want the screen to be scrolling to the top in the middle of an action.

Solution Part 2
What I eventually did was to replace the href=”#” with href=”javascript:;”, which is basically an empty line of Javascript. This stops browsers (tested on FireFox, IE 6 and Safari) from scrolling to the top.

So I end up with
<a class="frame_holder" href="javascript:;"><img src="foo" alt="bar" onclick="doStuff()"/></a>
instead of
<img class="frame" src="foo" alt="bar" onclick="doStuff()"/>
to make it work in Internet Explorer 6 (I have yet to test it on IE 7 *crosses fingers*).

UPDATE
Added reference to ‘javascript:;’ in the href attribute instead of ‘#foobar’. Thanks to Wade for reminding me. I was pretty green when I wrote this post, am a lot wiser now 🙂

Fine Tuning your Javascript: YUI Js lectures

Almost all the people I know who use Javascript have learnt it in bits and pieces. Myself, as well, have learnt Javascript on a need basis; if I run into a situation where I don’t know how the to handle it in the language, I look it up and proceed.

Very few people actually take the time to learn Javascript as a language, since the majority consider it to be a scripting language, something that is incomplete and not fully formed. This is probably the main reason why most of the Javascript code out on the web is crap.

With the rise of Web 2.0, Javascript has come into its own as the main source of behavior on web pages (HTML being the presentation and CSS being a bit of both I guess). Without Javascript, there would be no Web 2.0.

I came across a series of amazing lectures by Douglas Crockford, Yahoo!’s Javascript Architect. There are 3 series of lectures, each broken down into 3-4 smaller parts:

  1. The Javascript programming language (111 mins) (.ppt file)
  2. Advanced Javascript (67 mins) (.ppt file)
  3. An Inconvenient API: The Theory of DOM (78 mins) (.ppt file)

 

After going through the first series of lectures, I had so much of my code in mind that I wanted to rewrite (I haven’t gone through the other 2 series yet, but I found the first one really really useful). If you want to get your Javascript straight, these lectures are the best starting point. I really like Crockford’s style and the way he delivers (heck, he’s Yahoo!’s main Javascript dude, he HAS to be good).

It’s good to skim through the power point slides before and after watching the lectures, just to get a clear picture. But as in all cases of learning a new language, nothing beats actual coding. Keep these concepts in mind, and have a look at these proposed Javascript coding standards, and you’ll be on your way to writing good clean Javascript.