Introducing MooTools ElementSpy

By  on  

One part of MooTools I love is the ease of implementing events within classes. Just add Events to your Implements array and you can fire events anywhere you want -- these events are extremely helpful. ScrollSpy and many other popular MooTools plugins would be nothing without events. And think of DOM elements without events...terrible! Not knowing when someone clicked, hovered, etc. would completely defeat the purpose of JavaScript!

I wanted to take basic element events further. Sure I know when the value of an input changes (via onChange), but what about when another attribute changes? Or a style change? Or the change in a storage value? ElementSpy allows you to assign periodical checks on element attributes or other aspects of elements.

The MooTools Javscript

var ElementSpy = new Class({
	Implements: [Options,Events],
	options: {
		interval: 100
	},
	initialize: function(element,attribute,options) {
		this.setOptions(options);
		this.element = document.id(element);
		this.val = this.getter(attribute);
		this.interval;
		this.worker = function() {
			var value = this.getter(attribute);
			this.fireEvent('check',[this.val,value]);
			if(value != this.val) {
				this.fireEvent('change',[this.val,value]); //old,new
				this.val = value;
			}
			else {
				this.fireEvent('stagnate',[value]); //current
			}
		}.bind(this);
	},
	start: function() {
		this.interval = this.worker.periodical(this.options.interval);
		this.fireEvent('start');
		return this;
	},
	stop: function() {
		$clear(this.interval);
		this.fireEvent('stop');
		return this;
	},
	getter: function(attribute) {
		return $type(attribute) == 'function' ? (attribute.bind(this.element))() : this.element.get(attribute);
	}
});

The following are arguments, options, and events for ElementSpy:

Arguments

  • element: The element to spy on.
  • attribute: The attribute to spy on *or* a function that returns a value.
  • options: The class options.

Options

  • interval: (defaults to 100) The frequency in milliseconds that the element should be checked.

Events

  • change: Fired when the value has changed.
  • check: Fired every time the element is checked.
  • start: Fired when an element starts being spied on.
  • stop: Fired when you stop spying on an element

The MooTools ElementSpy Usage

var element = document.id('my-image');
/* simple: just watch an attribute */
var spy = new ElementSpy(element,'src', { 
	duration: 200,
	onChange: function(old,nu) { //alert when the image's SRC has changed!
		alert('Image SRC changed from ' + old + ' to ' + nu);
	}
});
//start spying on the image SRC!
spy.start();

This first usage is about as basic as it gets -- listening for an image SRC change.

/* difficult: watch a style */
var element2 = document.id('button2');
var spy2 = new ElementSpy(element2,function() {
	return this.getStyle('cursor');
}, { 
	duration: 200,
	onChange: function(old,nu) {
		alert('Change!  Value changed from [' + old + '] to ' + nu + ']');
	},
	onCheck: function(old,nu) {
		console.log('Check:  Value changed from [' + old + '] to ' + nu + ']');
	}
});
spy2.start();
element2.addEvent('click',function() {
	this.setStyle('cursor','pointer');
	(function() { spy2.stop(); }).delay(2000);
});

This second, more advanced solution listens for a change in CSS cursor and allows me to fire events accordingly.

Please keep in mind that this class can be harsh on the browser if overused so please use with care! I'd also like to hear your thoughts on the class. Like it? Dislike? Have improvement ideas? Let me know!

Recent Features

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • By
    Google-Style Element Fading Using MooTools or jQuery

    Google recently introduced an interesting effect to their homepage: the top left and top right navigation items don't display until you move your mouse or leave the search term box. Why? I can only speculate that they want their homepage as...

  • By
    MooTools Link Fading

    We all know that we can set a different link color (among other properties) on the hover event, but why not show a little bit more dynamism by making the original color fade to the next? Using MooTools 1.2, you can achieve that effect. The MooTools...

Discussion

  1. there is a typo in the stop options.

    “start: Fired when you stop spying on an element”

    great post (As usually)!

  2. David, this is very useful! Thank you! BTW, It looks like Harald Kirschner’s Observer class, but more functional :) Mootools FTW!!11

  3. Nice idea, David. Do you think this could be combined with native Javascript getter/setters for browsers that support them? I understand getters and setters are not very standard or supported, but it would be cool to use them when possible, right?
    https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters

  4. Guillermo Rauch

    Nice idea. Not sure if I’d implement it as a standalone Class myself though.

    Also, I would avoid the timer if DOMAttrModified is available:

    if (document.implementation.hasFeature('MutationEvents','2.0')){
      // subscribe to DOMAttrModified
    } else {
      timer
    }
    

    There’re many ways to approach this problem. Another would be to create a custom MooTools event.

  5. Also, another way to detect support is to check for the presence of the MutationEvent constructor

    if (document.implementation.hasFeature(‘MutationEvents’,’2.0′) || ‘MutationEvent’ in window)

  6. This is a sweet plugin, Thanks David !

  7. Sweet plugin, awesome site!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!