Accomplishing Common Tasks Using MooTools, jQuery, and Dojo III

By  on  

My love of the JavaScript frameworks knows no bounds. Unfortunately too many developers stick to one framework without taking the time to learn the others. The more frameworks you know, the better a programmer you will be and the more money you'll make. Let me show you how to accomplish a few more tasks using three JavaScript frameworks: MooTools, jQuery, and Dojo.

Calculate Element Dimensions and Position

Knowing not only the height and width of a dimension but it's top/left position from an offset parent or document body can be extremely helpful when trying to animate or move a DOM element.

MooTools

var dimensions = document.id('myElement').getDimensions();
/* returns:
{ 
	height: 4684,
	width: 1408,
	x: 1408,
	y: 4684
}
*/

jQuery

var myElement = jQuery('#myElement');
var position = myElement.position();
var dimensions = {
	height: myElement.height(),
	width: myElement.width(),
	top: position.top,
	left: position.left
};

Dojo

var dimension = dojo.coords('myElement');
/* returns:
{
	h: 4684,
	l: 0,
	t: 0,
	w: 1408,
	x: 0,
	y: 0
}
*/

Extend an Object

Extending an object means taking on object and merging a second objects properties into it. This is very helpful in merging default options with instance options.

MooTools

$extend(firstObject,{ anotherProperty:'anothervalue' });
//second arg is added to the first object

jQuery

jQuery.extend(firstObject,{ anotherProperty:'anothervalue' })

Dojo

dojo.mixin(firstObject,{ anotherProperty:'anothervalue' });

Stop an Event

Stopping an event is helpful when looking to execute functionality (usually an XHR request) when a link is clicked.

MooTools

$('myElement').addEvent('click',function(e) {
	e.stop();
});

jQuery

$('#myElement').click(function(e){ 
	event.stopPropagation();
	e.preventDefault();
	// (no internal method that does both)
});

Dojo

dojo.connect(dojo.byId('myElement'),'onclick',function(e) {
	dojo.stopEvent(e);
});

Load Content into an Element

Sure we can create an XHR request manually to load content into an element but why do that when your favorite lirbary can do that work for you?

MooTools

document.id('myElement').load('ajax/script.html');

jQuery

jQuery('#myElement').load('ajax/script.html');

Dojo

//as found on Pete Higgins' website:
//http://higginsforpresident.net/2009/12/140-characters-of-awesome/
dojo.extend(dojo.NodeList, {
	grab: function(url){
		dojo.xhr('GET', { url:url })
			.addCallback(this, function(response){
				this.addContent(response, 'only');
			});
		return this;
	}
});
dojo.query('#myElement').grab('header.html');

Get and Set HTML Content

Getting and setting HTML is a frequent JavaScript operation...yet each library handles it a bit differently.

MooTools

//get
var html = document.id('myElement').get('html');
//set
document.id('myElement').set('html','Hello!');

jQuery

//get
var html = jQuery('#myElement').html();
//set
jQuery('#myElement').html('Hello!');

Dojo

//get 
var html = dojo.byId('myElement').innerHTML
//set
dojo.byId('myElement').innerHTML = 'Hello!';

Use Element Storage

Element data storage is important because it allows you to store settings within the element itself -- perfect for defeating scope and context issues.

MooTools

//set
document.id('myElement').store('key','value');
//get
var value = document.id('myElement').retrieve('key');

jQuery

//set
jQuery('#myElement').data('key','value');
//get
var value = jQuery('#myElement').data('key');

Dojo

//set
dojo.attr('myElement','data-key','value');
//get
dojo.attr('myElement','data-key');

There you are -- more proof that the toolkits are one in the same, all except the syntax.  Do yourself a favor and learn more than one JavaScript framework -- you'll be better for it!

Recent Features

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

Incredible Demos

  • By
    Create a Dojo Lightbox with dojox.image.Lightbox

    One of the reasons I love the Dojo Toolkit is that it seems to have everything.  No scouring for a plugin from this site and then another plugin from that site to build my application.  Buried within the expansive dojox namespace of Dojo is

  • By
    Select Dropdowns, MooTools, and CSS Print

    I know I've harped on this over and over again but it's important to enhance pages for print. You can do some things using simple CSS but today's post features MooTools and jQuery. We'll be taking the options of a SELECT element and generating...

Discussion

  1. I like this post,keep working~

  2. RE: Stop an Event for jQuery, you should be able to juse “return false;”

    From http://api.jquery.com/bind/#event-object

    “Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.”

  3. I’m saddened by your interpretation of some of the Dojo syntax. first, you should use position() over coords(). coords() should be returning the x/y of the element, curious why it isn’t. It also includes a param to calculate the relative offset some the viewport (t/l)

    I would have written the stopevent version as:

    dojo.query("#myElement").onclick(dojo, "stopEvent"); // if this is all it's doing ...
    

    While the grab() function is admittedly full of awesome [humbly …] I would probably go the other way and simply issue an xhrGet call:

    dojo.xhrGet({
         url: "ajax/script.html",
         load: function(data){
               dojo.byId("myElement").innerHTML = data;
         }
    });
    

    No plugin required.

    And while there is a NodeList-data plugin/module available, it seems too tightly coupled to me — passing around data based on elements. imo, it is better to have data that may or may not reference an element. Object lookup is orders of magnitude faster than getAttribute. HTML5’s dataset is an interesting take on this, removing the getAttribute work in the few browsers that support it but in the end IE still exists.

    html5 dataset: http://svn.dojotoolkit.org/src/branches/dojo-fd/dojo/dataset.js
    NodeList-data: http://github.com/phiggins42/plugd/blob/master/NodeList-data.js

    Also, some of these examples go beyond simple syntax variations. Eg: jQuery.extend is chock full of syntatic magic (cloning, extending prototypes, sniffing if it’s itself, and so on). dojo.mixin simply mixes object references. I cannot speak to the Moo variant.

    Regards –

    • Per your comments:

      1. There seem to be a few dimension-related methods…perhaps a bit more documentation would help? :)

      2. The stopEvent thing is only a…setup…to do more within that method. I’m not sure how helpful just a stopEvent would be.

      3. innerHTML is probably better, but I really liked your grab script. That just shows me I shouldn’t try to pay homage to Pete Higgins!

      4. I chose to use element storage as it’s used with both jQuery and MooTools. Object storage is great but I have to play to the average with the three frameworks.

      Thanks for taking the time to comment.

    • 1. It is. A combination of bugs, and deprecation warnings() and something wrong with the parser not finding it … should be resolved soon. coords() is deprecated. Thanks for pointing it out. Bonus points for filing a bug.

      2. I assumed as much. I just like showing off the built in hitch() magic.

      3. Nooooo. I love grab(), else I wouldn’t have written a whole blog about it. It adds a bunch of pleasant syntax to a simple operation. but 9 of 10 times I need to do a tiny bit more than “chain some shit and load some remote content into my nodelist item”, so knowing the “longhand”, or even just how it all works internally (which was the topic of the blog) is a bonus.

      4. Well that’s what NodeList-data was doing. But the snippet you provided implied there was no data capabilities in Dojo, as you were simply stashing and removing the information from an attribute. The equiv in jQuery would be $(..).attr("data-something", blah, blah) … Likewise in Moo. NodeList-data provides a jQuery-like interface to node-data, based on object hashes (I presume Moo and jQuery both do it this way with their data() and store() implementations?). There is currently a proposal by Paul Irish to defer to native data-* attributes when using $().data, but afaik nothing has landed there. the html5 dataset API is cool, but only currently available in webkit nightly and ff4 (afaik) so it mostly defers to getAttribute calls anyway. All that said, I still say thinking about Data as it relates to the existing DOM is backwards, though convenient. Your DOM should be a representation of your data, not the other way around. dojo.data is “Dojo’s solution” there, though too much for some cases — hence NodeList-data/dataset plugins, though again it all ends up coming back to an attribute and a hash.

      “It’s just JavaScript.”

    • Yeah, to defend myself again, the Dojo API docs don’t say anything about deprecation. I’ll talk to someone about possibly changing that. Checking both the API *and* reference before using a method is not ideal.

  4. Absolutely. Me learning jQuery – while, coming from Moo, it frustrates the hell out of me – has definitely helped.

    I’m looking at Dojo with interest too. I’ll probably do that some time soon!

  5. Mootools FTW!

    Though the other libraries are good too. Good post

  6. Jostein

    Yeah yeah. You’re just showing off how nice MooTools is. ;)

    • @jostein

      I slightly disagree, I believe MooTools shows off how good MooTools is… :)

    • Best response EVER.

  7. Great job! Coming from dojo is easy to go with Mootools or jQuery now. Hard to decide wich to use. Though it’s hard to pick wrong, they’re all excelent.

    • If you’re looking for another toolkit to try out, and you’re coming from a Dojo background, be sure to go with MooTools. The syntax is a bit different but most of the functionality from Dojo is baked in, just with different syntax.

  8. El garch

    can’t choose any other Framework, Jquery is the best one :)

  9. Jerry

    Hey man ,the .load function is not working for me :(

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