MooTools Tip: Class.toElement

By  on  

Many of you may not know of a feature that's baked into MooTools' Class internals: Class.toElement. Class.toElement allows you to pass the $ (or document.id) method an instance of your class and the instance will be treated as an element.

The MooTools Class.toElement Usage

/* baking into the class */
var myClass = new Class({
	initialize: function(container,options) {
		this.container = $(container);
	},
	// .. lots more methods //
	toElement: function() {
		return this.container;
	}
});

/* usage */
var mc = new MyClass('wrapper');
$(mc).fade('out'); //fades the container out

This isn't a groundbreaking piece of code but it's just another example of the flexibility that MooTools affords its developers. Happy coding!

Recent Features

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

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

  • By
    MooTools Zebra Tables Plugin

    Tabular data can oftentimes be boring, but it doesn't need to look that way! With a small MooTools class, I can make tabular data extremely easy to read by implementing "zebra" tables -- tables with alternating row background colors. The CSS The above CSS is extremely basic.

  • By
    HTML5’s window.postMessage API

    One of the little known HTML5 APIs is the window.postMessage API.  window.postMessage allows for sending data messages between two windows/frames across domains.  Essentially window.postMessage acts as cross-domain AJAX without the server shims. Let's take a look at how window.postMessage works and how you...

Discussion

  1. Haven’t noticed this wonderful tiny yet so useful method before. Thanks for bringing this up :)

  2. jeremy

    i was actually just reading about this today.

    it seems often times the method is used to create the element that gets returned as well, in which case its important to make sure the method doesn’t re-define the element it returns.

    toElement: function() {
    if (this.element) return this element;
    return this.element = new Element(...);
    }
    
  3. Hey, that’s a useful thing! Didn’t know this before, THX for sharing!

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