Archive for the ‘Code Snippets’ Category

Javascript shorthand @ d’bug

November 5th, 2007 by Aaron N.

The d’bug blog has a nice little post on javascript shorthand that’s worth looking at if you don’t know these tricks. Stuff like declaring variable defaults with the logical OR or using ternary , etc. One thing to be careful of is type coercion. Basically if you say “if (x) …” you can get a false evaluation if x is an empty string, null, zero, or false. Check out the mootools functions $chk, $pick, and $defined for easy ways to avoid these kinds of things. You can also express conditionals using === and !== to ensure you are evaluating for the right condition.

/*

    -----------------------------------------------
    Conditional Shorthand 1
    -----------------------------------------------

    If "a" is not defined, or is not equal to true,
    then "a" is equal to "b".

    Longhand:

        var a, b;
        if ( !a ) {
            a = b;
        }

    Shorthand:

*/

var a, b;
a = a || b;

/*

    -----------------------------------------------
    Conditional Shorthand 2
    -----------------------------------------------

    If some condition is equal to true,
    then "a" is equal to "b", or else
    "a" is equal to "c".

    Longhand:

        var a, b, c;
        if ( true ) {
            a = b;
        } else {
            a = c;
        }

    Shorthand:

*/

var a, b, c;
a = ( true ) ? b : c;

Check out the whole article »

Snook: Accelerated DOM Scripting w/ Ajax, APIs, and Libraries

October 9th, 2007 by Aaron N.

About a year and a half ago I started focusing on javascript again. I’m not really a developer here at CNET (though you’d be hard pressed to tell) but javascript was a means to an end and I didn’t really have anyone here that could do the work, so I rolled up my sleeves, unaware that I’d be spending this much time on the subject. It’s a good thing I find this stuff fun.

Anyway, over the course of that time I learned a lot of the ins and outs of writing javascript well. I blogged about many of these discoveries along the way here on this blog. But if you’re just getting started with javascript, or you suspect that you’re writing things without really understanding them, or maybe you’re using javascript the “old way” or whatever, where do you start?

All my tutorial work just assumes that you know a lot of these ins and outs and doesn’t spend much time talking about the whys of “new” javascript methodology.
Over my lunch break I thumbed my way through Jonathan Snook’s Accelerated DOM Scripting with Ajax, APIs, and Libraries and if you feel like you need a primer on how to do “modern” javascript, it’s a great starter book. It covers a lot of stuff from the DOM to Ajax, closures and more.

It touches on Libraries (prototype, YUI, jQuery, Mootools, etc.) but it’s not going to teach you to use them. Instead it shows you a lot of the conceptual stuff going on in frameworks and helps you understand modern browsers and the javascript concepts that they implement.

If you’re just getting started with javascript, I highly recommend it. Even if you’re already using a framework, you can pick up some good practices from the examples and illustrations and detailed under-the-hood information.

Despite it being a rather technical book, it’s written so that even if you’re new to javascript you can learn a lot from it. It will help if you have experience with programming in general, as it assumes you have a general understanding of object oriented practices, but beyond that the book is very approachable.

-A.N.

Selector Sugar for Mootools

August 9th, 2007 by Aaron N.

Mootools contributor Digitarald (i.e. Harald Krischner) posted a while back about Mootools selector goodness that’s been added. CSS3 selectors arrive and it’s all nice stuff.

The $$() function in MooTools uses CSS selectors to select Elements from the DOM. Since last week, basic CSS2 was supported, but now the developers added more selector features. Check out the slick speed test and the blog entry about the tale of pseudoselectors describing the details and the development. I’ll describe some basic about the selectors here …

That was already possible

// Select all anchors
$$('a');

// Select all anchors inside list items
$$('li a');

// Select all anchors with class "ajaxified" inside an element with "menu" id
$$('#menu a.ajaxified');

// Select all anchors and images with the "title" attribute
$$('a[title], img[title]');

// Select all anchors with the "href" attribute, beginning with "http://" and with "ajaxified" class
$$('a.ajaxified[href^="http://"]');

$$ returns an Array of Elements, extended with Elements methods, so you can do this:

// Adding an ajax request to all ajaxified menu anchors
var menuAjax = new Ajax('', { // url is empty, we set it dynamically
	autoCancel: true, // when a new request starts and the previous one is running, its cancelled
	update: $('content'), // the target
	evalScripts: true // maybe we have script tags in the content
})

$$('#menu a.ajaxified').addEvent('click', function(e) {
	menuAjax.url = this.getProperty('href');
	menuAjax.request();
	return false; // see NOTE
})

This simple example adds ajax loading to menu items using the href url. Now you can add e.g. effects when the content is injected, a spinner when the request starts, selected items and more fancy stuff.

NOTE: This event handling is new in the svn trunk. You no longer need to use new Event(e), bindWithEvent or bindAsEventListener when you use Element::addEvent. The given event is automatically the extended cross-browser Event class and of course this (the scope in your event callback) is the Element. Furthermore you can return false to stop the event propagation.
When you want to use this example with MooTools 1.11, simply stop the event with new Event(e).stop().

And what is new?

The new CSS3 selectors are not ALL available like shown in w3c-specs, we added the useful ones. Of course the whole thing is super fast, uses XPath internally for cool browsers and is, like most things in MooTools, extendable.

// All list items which are childnodes of ul#top
$$('ul#top > li');

// all list items following li.head with the same parent node
$$('li.head ~ li');

// all anchors containing the word "Hello"
$$('a:contains("Hello")');

// The selector implementation and parsing allows also short-hand notations ...

// first list item in an ul element
$$('ul li:first');
// same as
$$('ul li:nth-child(1)');
// same as
$$('ul li:first-child');

// every second li inside an ul, starting from the second
$$('ul li:nth-child(2n)');
// same as
$$('ul li:nth-child(even)');
// same as
$$('ul li:even');

// simple and fast zebra table in one line
$$('table > tr:odd').addClass('odd');

Read more on The MooTools Blog – Selectors on Fire

Fx.Sort

July 19th, 2007 by Aaron N.

I got a little bored last night and banged this out. A little 2K effect for resorting elements with an effect. More info in the wiki, download in the svn. Read the rest of this entry »

Latest mootools tutorial: how to write a Class

June 25th, 2007 by Aaron N.

Here’s a step-by-step and line-by-line example of how to write a Mootools Class. I wrote this example for a javascript class I taught here at CNET for our developers and figured I’d share with everyone else.

Snook on Private Methods

June 19th, 2007 by Aaron N.

Jonathan Snook has a nice write-up about using private methods in javascript.

With JavaScript, you can create private methods and properties using what Yahoo describes as the module pattern. Here’s the basic construct, including a private method:

MyObject = function(){

  var privateMethod = function(){ /* do stuff */ };

  var obj = {
    publicProperty:5,
    publicMethod:function(){ /* do stuff */ };
  };

  return obj;
}(); // run it right away

If you’re not familiar with this pattern, it’s really quite cool. It takes advantage of closures, allowing the public methods to access the private methods. I’ve been using this approach in my recent work and it feels nice and works well.

New Clientside Scripts, 3rd Party Scripts added

June 14th, 2007 by Aaron N.

So in the last week or so I’ve been working on a bunch of CMS related tasks. I’ve added some new stuff and, for the first time, 3rd party scripts are now in our repository. Why? Well, why re-invent the wheel, right? In some cases I’ve implemented a few changes in these libraries, while in others I’ve rewritten them a LOT. You’ll find working examples and details in the wikitorials and I’ll be updating our docs shortly. Read the rest of this entry »

CNET javascript update (r90)

May 16th, 2007 by Aaron N.

I released a lot of code today including a bug fix that was probably pestering any of you with r87.

  • product.picker.js now has no picklets; these are in the implementations/picklets directory
  • ProductPicker now detects if there is no doctyp and, if not, sets the position of the picker to be fixed (no IE6 support)
  • small docs update in element.cnet.js
  • added new picklet: CNETProductPicker_PricePath
  • added new picklet: NewsStoryPicker_Path
  • new file: clipboard.js (allows you to insert text into the OS clipboard)
  • new file: html.table.js (automates building html tables)
  • new file: element.forms.js (for managing text inputs – get selected text information, insert content around selection, etc.)
  • fixed an error in stickyWinHTML (ie reserves “class” for member names)
  • converted window.onDomReady references to window.addEvent(‘domready’..
  • updated css for stickyWin.js to avoid namespace conflicts with the css class “clearfix”

Read the rest of this entry »

Sorting javascript arrays

May 9th, 2007 by Aaron N.

Bas Wenneker has a nice little article over at solutoire.com on sorting javascript arrays. The docs over at Mozilla on Array.sort demonstrate the same stuff, but Bas’s article is a quick read that’s worth it if you ever see yourself working with data this way.

objectArray.sort(callbackFunc);

/**
 * After sorting the objectArray will be like this:
 * [
 * 	{firstname: 'Will', 	lastname: 'Brown',	age: 28},
 * 	{firstname: 'John', 	lastname: 'Doe',	age: 25},
 * 	{firstname: 'Marie', 	lastname: 'Doe',	age: 28},
 * 	{firstname: 'Sarah', 	lastname: 'Doe',	age: 25},
 * 	{firstname: 'James', 	lastname: 'White',	age: 28},
 * 	{firstname: 'George', 	lastname: 'Williams',	age: 25}
 * ]
 */

new: Element.pin

May 3rd, 2007 by Aaron N.

Here’s a little Mootools extension that you might find useful. I’m using it my StickyWin classes to allow the user to “pin” it in place so it won’t move if they scroll.

$('fxTarget').pin()

Execute the example, then scroll. That’s it. You can unpin it if you like:

$('fxTarget').unpin()

(note, in this example because of the way my little fxTarget helper works, unpin will break the drag behavior, but that won’t happen in other instances).

I’ve added .pin and .unpin to StickyWin, too.