O'Reilly

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!

Track.js Error Reporting

Upcoming Events

Recent Features

  • 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...

  • How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • Build a Toggling Announcement Slider Using MooTools 1.2

    A few of my customer have asked for me to create a subtle but dynamic (...I know...) way for them to advertise different specials on their website. Not something that would display on every page, but periodically or only the homepage. Using a trick...

  • Google Font API

    Google recently debuted a new web service called the Font API.  Google's Font API provides developers a means by which they may quickly and painlessly add custom fonts to their website.  Let's take a quick look at the ways by which the Google Font...

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!