Code Snippets: Posts

CiUI Dev on Google Code

I’ve created a new development repository on Google Code. I wanted to have a separate development environment for people to work on the library without having to work off of the entire CNET Javascript framework repository. I’ll be posting CiUI-only releases there before merging them with Clientside’s repository.
You can also file CiUI specific bugs and feature requests on there. If you’re interested in joining in the development, please come discuss your ideas to our Google group.

CiUI Dev Google Code repository:
http://code.google.com/p/ciui-dev

CiUI Group
http://groups.google.com/group/ciui

MochaUI - The future of StickyWin?

Ajaxian today posted about Greg Houston’s MooTools-based MochaUI class that draws draggable, resizable, rounded-corner and dropshadowed boxes without using images. It uses canvas tags and Google’s ExplorerCanvas. Looks like Greg didn’t take advantage yet of Olmo Maldonado’s MooCanvas, but maybe he’ll upgrade. His demo works well across browsers and platforms (with a small bug in FFox/Mac that custom scrollbars can fix).

It might be a while before you see these on CNET, but I’m starting to finally see a happy place between our design and production teams where design gets their rounded corners and dropshadows, and production doesn’t have to deal with the headaches that come with them. I also expect that we’ll see a bunch more development around ExplorerCanvas (and MooCanvas) in the near future.

Greg’s code seems to be pretty well-rounded, but he hopes to add some new features (including modal windows and the aforementioned custom scrollbars). He says this is “an on going [sic] exercise to help me become more familiar with both MooTools and the canvas tag.” Keep up the good work, Greg.

I might add that Aaron lamented via IM, “stickyWin’s days are numbered.” It’s been a good run, stickyWin, but I don’t think we’re done with you quite yet.

Javascript shorthand @ d’bug

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.

JavaScript:
/*

    -----------------------------------------------
    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;

drag to resize


Check out the whole article »

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

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

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

JavaScript:
// 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://"]');

drag to resize


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

JavaScript:
// 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
})

drag to resize



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.

JavaScript:
// 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');

drag to resize


Read more on The MooTools Blog – Selectors on Fire

Fx.Sort

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 »

Latest mootools tutorial: how to write a Class

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

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:

JavaScript:
MyObject = function(){

  var privateMethod = function(){ /* do stuff */ };
 
  var obj = {
    publicProperty:5,
    publicMethod:function(){ /* do stuff */ };
  };
 
  return obj;
}(); // run it right away

drag to resize


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

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 »

CNET javascript update (r90)

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 »

Categories

Archives

Links and whatnot