Entries Tagged 'javascript' ↓
August 22nd, 2008 — javascript, jquery
I had a challenge to get four divs to fade in sequentially.
Writing this out the long way is not really my favorite:
$("#vehicle1").fadeIn("slow", function(){
$("#vehicle2").fadeIn("slow", function(){
$("#vehicle3").fadeIn("slow", function(){
$("#vehicle4").fadeIn("slow");
});
});
});
Ewwww. right?
After some conversation in the #jQuery IRC channel, I present two classier ways of accomplishing the same thing:
Self-executing callback chaining
(function showVehicle(elem){
elem.fadeIn('slow',function(){
$(this).next().length && showVehicle($(this).next());
});
})( $("div.vehicle:first") );
Custom event triggering (via: ajpiano)
$('div.vehicle')
.bind('showVehicle',function(e) {$(this).fadeIn('slow',function(){
$(this).next().length && $(this).next().trigger("showVehicle");
})})
.eq(0)
.trigger('showVehicle');
May 13th, 2008 — front-end development, javascript
Very often you'll have events happening asynchronously, but you need to wait until one has completed before you fire the second.
And you may not have the ability of attaching a callback function to the first.
In my less wise days I'd say "Lets just setTimeout it for a couple seconds..." but always felt really dirty about it.
A classier approach I've used lately is to poll for a change. Here I'm using the gmail greasemonkey API and waiting for it to load in before I start using it:
gmonkey.load("1.0");
// this is a self-executing anonymous function that uses setTimeout to call itself
// at 50ms intervals until the isLoaded variable resolves as true.
(function(){
if (gmonkey.isLoaded){
// do stuff i want to do with the API
gmonkey.get('1.0').addNavModule('notepad', '<iframe src="http://aaronboodman.com/halfnote/"></iframe>');
} else {
setTimeout(arguments.callee,50);
}
})();
I found myself doing this a lot when loading in multiple external resources and playing with them.. So to generalize the code I wrote executeWhenLoaded():
// executeWhenLoaded() will be overloaded with as many arguments as i want to check for presence.
function executeWhenLoaded(func){
for (var i = 1; i<arguments.length; i++){ // for loop starts at 1 to skip the function argument.
if (! window[ arguments[i] ]) {
setTimeout(arguments.callee,50);
return;
}
}
func(); // only reaches here when for loop is satisfied.
}
// and in use:
executeWhenLoaded(function(){
console.log(session.data);
},'session'); // session will return a value when the whatever preceding functionality is done.
executeWhenLoaded's first argument is the function to call, it can an unlimited number of arguments, which are all strings that reflect objects in the global namespace that have to be present in order to execute that function.
Update: In the comments, ProggerPete notes that this is not cross-browser compatible.. yet! In IE6, at least, the browser loses the original reference to the arguments object when it cycles through on the arguments.callee call. He offers a fix below.
April 21st, 2008 — hacks, javascript
Let's take a list of countries that was originally alphabetized in English, but is now translated to French.
var arr = ["Argentine", "Australie", "Autriche", "Belgique", "Brésil", "Canada", "Chili",
"Chine", "Costa Rica ", "République Tchèque", "Danemark", "Équateur", "El Salvador ",
"Finlande", "France", "Allemagne", "Guatemala", "Hong Kong", "Hongrie", "Inde", "Irlande",
"Italie", "Japon", "Corée du Sud", "Luxembourg", "Mexique", "Pays-Bas", "Nouvelle-Zélande",
"Norvège", "Panama", "Pologne", "Portugal", "Russie", "Slovaquie", "Espagne",
"la Suède", "Suisse", "Turquie", "Royaume-Uni", "Uruguay", "États-Unis"]
You can see the incorrect sort order for Germany ("Allemagne") and the US ("États-Unis").
Running the standard javascript Array.sort() will sort it according to the American English language:
arr.sort();
/*==>
["Allemagne", "Argentine", "Australie", "Autriche", "Belgique", "Brésil", "Canada", "Chili",
"Chine", "Corée du Sud", "Costa Rica ", "Danemark", "El Salvador ", "Espagne", "Finlande",
"France", "Guatemala", "Hong Kong", "Hongrie", "Inde", "Irlande", "Italie", "Japon",
"Luxembourg", "Mexique", "Norvège", "Nouvelle-Zélande", "Panama", "Pays-Bas", "Pologne",
"Portugal", "Royaume-Uni", "Russie", "République Tchèque", "Slovaquie", "Suisse", "Turquie",
"Uruguay", "la Suède", "Équateur", "États-Unis"] */
Note the misplacement of the last three entries. A real internationalized sort of this would be a huge motherbitch to implement, but here is a quick and hacky way to get your ducks in order:
arr.sort(function(a,b){
function normalize(str){
return str
.toLowerCase()
.replace(/è|é|ê|ë/,'e').replace(/ò|ó|ô|õ|ö/,'o').replace(/ì|í|î|ï/,'i')
.replace(/à|á|â|ã|ä|å|æ/,'a').replace(/ù|ú|û|ü/,'u');
}
a = normalize(a);
b = normalize(b);
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
});
/*==>
["Allemagne", "Argentine", "Australie", "Autriche", "Belgique", "Brésil", "Canada", "Chili",
"Chine", "Corée du Sud", "Costa Rica ", "Danemark", "El Salvador ", "Équateur", "Espagne",
"États-Unis", "Finlande", "France", "Guatemala", "Hong Kong", "Hongrie", "Inde", "Irlande",
"Italie", "Japon", "la Suède", "Luxembourg", "Mexique", "Norvège", "Nouvelle-Zélande",
"Panama", "Pays-Bas", "Pologne", "Portugal", "République Tchèque", "Royaume-Uni",
"Russie", "Slovaquie", "Suisse", "Turquie", "Uruguay"] */
It's not perfect (I bet that "la Suède" should actually be in the S's), but it'll get you a bit closer without too much effort.
April 1st, 2008 — hacks, javascript
If you're incredibly popular on the internet, like me, then I can hear you crying for help. :)
Friend requests littering your inbox can get annoying. They certainly don't need your attention right now, so why not through them to a more passive information consumption area: RSS. That way you can process them en masse, when you're ready to.
First, we use the filters in Gmail to identify all friend request emails.
- Set up a new filter.
- In the subject area put in this text:
{"friend request" "is now following you" "newest contact" "friends on yelp" "added you as a" "has requested your trust" "wants to be your friend" "invited you to connect" "would like to be added"}
- Click next, then select Skip the Inbox
- Check Forward it to and in the box put in a unique-email-address @ mailbucket.org. (For example: paulsfriendrequests@mailbucket.org) This will be a public feed, so... yeah.
- Click Create Filter

Your newly created RSS feed will be at http://mailbucket.org/unique-email-address.xml.
This filter will catch all friend requests from: Myspace, Facebook, LinkedIn, Flickr, Spokeo, Twitter, Yelp, and Plaxo Pulse. (And should be pretty trivial to add new ones. :)
February 9th, 2008 — javascript
I'm working with some code from MultiMap (basically a Google Maps clone), and unfortunately their API doesn't support real internationalization. There are a number of strings hardcoded in English in their remotely-hosted JS, so this is my deliciously evil way of rectifying the situation.
I first started out redefining their functions in entirety, but that becomes "dangerous" when they modify a bit of code for a bug fix or something. This revised approach slips in like an evil drunken ninja and only replaces the offending parts. It's still completely crazy, but sometimes there are no better options...
// WARNING!! This is such a massive hack. Oh-so-hackalicious
// Problem: Multimap doesnt allow internationalization of its buttons, etc.
// Solution: Redefine their JS functions to use variables that are internationalized.
// Assumption: That these internal function names stay the same.
// Risk: If function names change, this code will (probably) silently fail.
// The following statements change the right-click context menu items and the map/aerial/hybrid buttons.
// Instead of hard-coded strings, it will use a variable which we control.
// ON TO THE HACKS!!
// Hack 1: modify the mmjr() and mmfl() functions with funcName.toString().replace()
// Hack 2: use eval() to set the definition
// Hack 3: browser sniff because IE and FF handle toString()'d strings differently (single-quote vs double-quote)
var isIE = $.browser.msie; // jQuery browser sniff.
eval(
"mmki.prototype.mmjr = " +
mmki.prototype.mmjr
.toString()
.replace( isIE ? "'Move map to here'" : '"Move map to here"' , 'i18n.retailLocator.moveMapToHere')
.replace( isIE ? "'Zoom in to here'" : '"Zoom in to here"' , 'i18n.retailLocator.zoomInToHere')
.replace( isIE ? "'Zoom out from here'" : '"Zoom out from here"', 'i18n.retailLocator.zoomOutFromHere')
);
eval(
"MultimapViewer.prototype.mmfl = " +
MultimapViewer.prototype.mmfl
.toString()
.replace( isIE ? "'Map'" : '"Map"', 'i18n.retailLocator.map')
.replace( isIE ? "'Hybrid'" : '"Hybrid"', "i18n.retailLocator.hybrid")
.replace( isIE ? "'Aerial'" : '"Aerial"', 'i18n.retailLocator.aerial')
);
January 31st, 2008 — javascript
I've put together all the feeds and blogs that I follow that cover front-end development.
Here is the OPML file: front-end-development-feeds.xml.opml
All the classics like Ajaxian and A List Apart are in here.. but also more technical ninja developers like John Resig, Hedgerwow and Peter Michaux.
If you currently use a RSS aggregator (like Bloglines, Google Reader, or Netvibes) you can import this file right in.
iGoogle won't take an OPML file but you can do each RSS feed individiually.
You can also preview what's in it here: http://www.bloglines.com/public/molecular-frontend-feeds
January 27th, 2008 — javascript
// code yanked from the Yahoo media player. Thanks, Yahoo.
if (! ("console" in window) || !("firebug" in console)) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group"
, "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {};
}
January 26th, 2008 — javascript
Updated 2008.01.28: Great idea from Marc and Hendrik. Very slick.
function concatenate(){
// return arguments.join(''); // won't work. arguments is not a real array.
// return [].splice.call(arguments,0).join(''); // old 'n busted
return Array.prototype.join.call(arguments,''); // new hotness
}
concatenate('good',2,'go');
// ==> 'good2go'
January 14th, 2008 — javascript
I've often had to set up onload events that execute for only a single page. I've both hardcoded those function calls right into the markup and I've done page detection in a shared js file (parsing the current URL, ew!). Neither solution is rather pretty. The below solution keeps things unobtrusive.
Set up the body tag with an ID that identifies the page, such as:
Over in your javascript, set up your page init code in an object literal:
var siteNameSpace = {
homepage : {
onload : function(){
// do this stuff.
}
},
contact : {
onload : function(){
// onload stuff for contact us page
}
};
Your document ready code executes for the same for all pages:
jQuery:
$(document).ready( siteNameSpace[ document.body.id ].onload );
Prototype:
Event.observe(window, 'load', siteNameSpace[ document.body.id ].onload );
YUI:
YAHOO.util.Event.onDOMReady( siteNameSpace[ document.body.id ].onload );
However this will fail if that object (and onload function) are not defined.
But you can fix it with a little more code..
//jQuery version
$(document).ready(
function(){
var NS = window.siteNameSpace, bID = document.body.id;
if(NS && NS[ bID ] && (typeof NS[ bID ].onload === 'function')){
NS[ bID ].onload();
}
}
);
January 13th, 2008 — javascript
I'm interested in understanding all the selector engine code. In order to watch the development from the most basic to the quickest, I wanted to gather all the data points. Take a look, as you can see, Jack Slocum was definitely right when he said "selector processing power has gone from Pinto power to a Mustang GT 500."
Update: Added Base2, CssQuery1.0. Corrected jQuery launch date.
Update: Added Dojo 0.9, NWMatcher.
(Drag to navigate timeline)
Leave a comment if I left anything out.