Treehouse

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!

ydkjs-5.png

Recent Features

  • Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today’s websites and devices become ever more varied, a plethora of responsive images...

  • Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Incredible Demos

  • MooTools TextOverlap Plugin

    Developers everywhere seem to be looking for different ways to make use of JavaScript libraries. Some creations are extremely practical, others aren't. This one may be more on the "aren't" side but used correctly, my TextOverlap plugin could add another interesting design element...

  • Create a Download Package Using MooTools Moousture

    Zohaib Sibt-e-Hassan recently released a great mouse gestures library for MooTools called Moousture. Moousture allows you to trigger functionality by moving your mouse in specified custom patterns. Too illustrate Moousture's value, I've created an image download builder using Mooustures and PHP. The XHTML We provide...

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!