Code Snippets: Event Scripting: Posts

Confirmer widget

Helping out our CMS group today I hacked out a new little widget class called "Confirmer" that handles notifying the user when something they've done on the page requires some sort of notice. An auto-save, or the failure to auto-save, or any other sort of message.

It's designed to be unobtrusive so it doesn't annoy the user too much if it happens a lot. You can have the prompt inline in the page or floating over it. The message just fades in and then back out. It comes with default styles that can easily be overridden, the message displayed can be changed every time you call it, and its easy to position it relative to an element or at the edge of the screen.

Quick example:

JavaScript:
new Confirmer().prompt(); //watch the upper right of your screen
new Confirmer().prompt(); //watch the upper right of your screen

drag to resize


More examples and details in the wikitorial.

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

DomReady, DomPolling, and window.onload revisited

Via Ajaxian is this post revising the age-old window.onload problem. I tried to write a dom polling method that would re-evaluate the dom every few milliseconds maybe 3 or 4 months ago but got distracted. Here's the work of smarter and less easily distracted people than I, and it's worth reading (even if you skip to the end). Maybe we'll work this into Mootools.

Peter Michaux has written a detailed post on the window.onload problem:

The goal of unobtrusive JavaScript programming it to separate the JavaScript behavior from from the HTML content and is analogous to the goal of unobtrusive CSS design to separate the CSS presentation from the HTML content. Separation of presentation and content has been possible for years but there is one wrinkle standing in the way of completely separating the behavior. This article is about previously suggested techniques to enable this separation, their problems and a new option that combines the strengths of the current techniques with an extra bonus into a new robust solution.

| Read the rest »

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.

Keywatcher.js - capture key presses (Mootools)

Here's a nice little extension I found on the mootools forums. It let's you assign an action to any element when the element has focused and the user clicks a key. I haven't played around with it yet, but it's super small and looks useful for form inputs and whatnot. Credit goes to BlackMac. | Read the rest »

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 and 3rd party widgets

I have several classes that I've written for use with Mootools that I'll be posting about soon. I thought I'd go ahead and point to this great little slider widget over at lenhatanh.pebox:

slider.gif

I know that Valerio over at mootools is planning a plugin repository for things like this, which I think will really help move that framework forward. In the mean time, I'll probably take things like this and move them into our own global framework after testing them out so that developers here can make use of them.

Rewrite of Behaviour.js in the CNET framework (mootools)

Huh. So this was eaiser than I thought.

In the Download.com Watch List profile page we use the Behaviour library to define a bunch of functionality (er, I mean "I use..." as I wrote all this over a year ago). We're going to replace Prototype with our new framework (based mostly on Mootools). Behaviour will work in the environment, but it's 8K that I don't really want to keep around. So, what the hell, let's try and rewrite it with Mootools. Well, here it is:

JavaScript:
var BehaviourBaseClass = new Class({
    initialize: function(){
        this.behaviours = [];
        var bhvr = this;
        Event.onDOMReady(function(){bhvr.apply()});
    },
    register: function(actions){
        if(! this.behaviours.test(actions))
            this.behaviours.push(actions);
    },
    apply: function(actions) {
        if ($type(actions)!='array') {
            actions = this.behaviours;
        }
        actions.each(function(bhvrs){
            for (bhvr in bhvrs){
                try {
                    if($type(bhvrs[bhvr])=='function') {
                        $S(bhvr).each(function(el){
                            bhvrs[bhvr](el);
                        });
                    }
                } catch(e){}
            }
        });
    }
});
var Behaviour = new BehaviourBaseClass();

drag to resize


...which compresses down to 425 703 Bytes. Not bad.

Update
Ok, so I rushed to press a little. This code didn't work when I put it into place. I fixed it, but that brought the file size up to 703 Bytes instead. Still, it's a 10X reduction...

event:Selectors - Behaviour +

I just happened upon event:Selectors. It's very similar to Behaviour.js (the author's spelling, not mine) in most respects, though its much smaller (72 lines / ~2k) and has some nice added functionality using Prototype shortcuts (Behaviour is stand-alone and duplicates a lot of Prototype stuff and is, therefore, larger).

Basic usage:

var Rules = {
   '#icons a:mouseover': function(element) {
     var app = element.id;
     new Effect.BlindDown(app + '-content', {queue: 'end', duration: 0.2});
   },

   '#icons a:mouseout': function(element) {
     var app = element.id;
     new Effect.BlindUp(app + '-content', {queue: 'end', duration: 0.2});
   }
 }

Now, this alone is nice, but nothing exceptional. You could do the same thing with prototype thusly:

Event.observe(window,"load",function() {
  $$('#icons a').each(function(tag) {
    Event.observe(tag,'mouseover', function() {
      var app = tag.id;
      new Effect....
    });
  });
});

Ok, so it's definitely longer to do without it, but not terribly so. But what really gets me excited is this:

 '#footer:loaded': function(element) {
    element.setStyle({backgroundColor: '#ccc'});
  }

This will apply the code to the element once it's loaded. That's just awesome. That's just awesome times five. Wait, it gets better: it will also apply all your rules to your Ajax responses, too (if you want it to). This means when you bring in a chunk of html into the DOM you don't have to set up all your events on it again.

It has a few other nice touches (you can, for instance, apply these events to more than one selector, for instance). Check it out.

A DOM Ready Extension for Prototype

Holy cow this is awesome.

via ajaxian: original post

Dean, John, Matthias and a load of other people were working on a really robust solution to the DOM Ready problem. In case you haven't seen Dean's post, they did it and it is good shit. If you want to read more of an explanation head over to Dean's site.

I've been waiting for, but in a very idle way, not doing much about, a really solid solution to this for a long time. It just so happens to be extremely useful for a certain Rails plugin I'm working on with Luke Redpath so as soon as it was written I knew I needed to extend Prototype to use this new technique.

So, here's an extension to Prototype that allows you to attach one or more functions that will be executed as soon as the DOM is ready to work with. This will not wait for images or other assets to load like window.onload does.

Here's the script: domready.js

To use it simply add a script tag after your prototype.js script tag or append the code to the bottom of prototype.js.

Then, to execute a function when the DOM is ready:

Event.onDOMReady(function() { //stuff here! });

You can call the function repeated times to add more functions to be triggered if you need to.

Categories

Archives

Links and whatnot