Code Snippets: Manipulating the DOM: Posts

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

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 »

IE and “Operation Aborted”

Internet Explorer's behavior sometimes really, really makes me angry.

We recently rolled out a copy of our javascript libraries after much testing and, a few hours later, discovered a page on our site that IE was barfing on. Specifically, the page would load about half way and then announce that it could not load the page (despite the fact that it's clearly loaded behind the error message) and then present you with its generic "page not found" content.

I've seen this behavior before and generally know what to look for, but it's a huge pain because the page is gone and your only method for debugging it is to slowly remove code, line by line, until it stops doing it. Then you put things back bit by bit until you narrow it down to the offending line. It's painstaking work and the constant error popping up begins to really grate.

So why does IE do this?

Perhaps I should use "when" instead of "why" in that header, because I don't really know why the developers of IE would do this.

Update: Bit thanks to Jon in the comments for turning me on to this MSFT support page about this topic. I've updated this article here to more accurately describe the problem. More detail can be found in the MSFT article.

IE does this when you attempt to modify a DOM element before it is closed. This means that if you try and append a child element to another and that other element (like the document.body) is still loading, you'll get this error. This will occur if you use .appendChild (which in Mootools includes .adopt, .injectInside, .injectBefore, etc.) or if you use Element.innerHTML = "" (or in Mootools, the .setHTML method). | Read the rest »

Mootools Beginner’s Example

If you are new to javascript or Mootools, you should:
1) Read the docs
2) Read the Mootools Tutorial

Now, the problem with the Tutorial is that it shows you snippets of how Mootools work, but doesn't put them all together to show you how to actually do things on a page.

So in an effort to help people see the right way to write code (well, at least how I write code; "right" is definitely subjective with javascript), as well as how to use the accordion and things like Fx.Slide, I've authored a simple little page that demonstrates these things and comments them line by line.

So:

3) View the source of the Mootools Beginner's Example

Mootools 1.0 goes gold, CNET Libraries WikiTorial

Mootools 1.0 is out. Fancy new site design and docs.

We've already refactored all our code for 1.0, though it is not yet released to the CNET site. We're entering into QA now...

I've also released the second part of my wiki tutorial series, this time giving working examples of all the CNET common code. The CNET Libraries are comprised of common code (widgets, shortcuts, etc.) and implementation code - code that is specific to a given page or application. The implementation code is usually just implementing and executing functions and libraries in the common portion of the library. The wikitorial for the CNET common code focuses on this generic content. Form validation, date pickers, carousels, etc. Dig in! Oh, and if you have a chance, Digg the tutorials, too. You'll find shortcuts to do that in the right navigation column in the tutorials.

Mootools Primer, CNET Libraries online

Hi gang,

I've been at work on a mootools primer as a tutorial for those who want to use the library but don't know a lot about javascript. It's replete with working code examples that you can execute right in the browser and see the result. | Read the rest »

Mootools

Well crap. 1) I love the mad4milk guys (makers of moo.fx, moo.ajax, moo.dom, prototype.lite). 2) their new framework looks AWESOME. 3) as always, their libraries are SUPER TINY.

But damn, now I have to learn something new, and maybe rewrite a bunch of crap. This is the problem with javascript. Still, when Prototype + Scriptaculous is 100K, you gotta admire their ability to crank something out in under 20K that will get you nearly the same thing.

The Mad4Milk team (the minds that brought the world moo.fx) have unleashed a brand new, very impressive Javascript library out onto the web - MooTools.

mootools is a very compact, modular, Object-Oriented javascript framework. Its unique design makes it extremely crossbrowser, easy to use, and a snap to extend with your own code. It comes with a choice of more than fifteen scripts, plugins and addons, including Effects (moo.fx) Ajax (moo.ajax), Dom Navigator (moo.dom), Drag and Drop, Sortable lists, cookies Manager and many more.

There aren't any demos of the functionality quite yet (as of the date of this post), but you can download the first release of thise powerful little tool.

You can also check out what Jonathan Snook has to say about it, having already downloaded and worked with it a bit. He's also created a simple tutorial on using the new library to create a drag-and-drop example.

Article on Writing Custom Iterators for Prototype from Encytemedia

via ajaxian: read the full article

The DOM can be a painful beast at times. When you ask for the childNodes of an element, most of the time you're just wanting the element nodes only and you'd like to completely ignore the text nodes. Using Prototype, you could write something like the code below:

element = $(element);
element.cleanWhitespace();
$A(element.childNodes).each(function(element) {
  element.setStyle({color: '#ccc'});
});

That would be a quick fix, but remember, we're not supposed to be repeating ourselves. | Read the rest »

Linkdump

Sorry about the non-annotated linkdump. Aaron's always after me to post stuff here instead of emailing him links to new things I find, but I just don't have time to describe all these sites. At least I categorized them... | Read the rest »

Prototype Tutorial

I read through about half of this so far and it's great. Lots of info on how to make use of prototype's powerful scripting shortcuts and plenty of best-practices examples. via Ajaxian: | Read the rest »

Categories

Archives

Links and whatnot