MooTools Tip: Adding Events During Element Creation

By  on  

One mistake I've made in the past with my MooTools elements is adding events to them after I've created and injected them into the page. An example of this would be:

var a = new Element('a',{
	href: 'https://davidwalsh.name',
	rel: 'lightbox',
	text: 'David Walsh Blog',
	title: 'David Walsh Blog: Best on the Web!',
	'class': 'shoutout',
	styles: {
		color: '#0f0',
		display: 'block'
	}
});
a.inject($('description'));

a.addEvents({
	click: function(e) {
		e.stop();
		console.log('Clicked!');
	},
	mouseenter: function(e) {
		e.stop();
		console.log('You are on top of me!');
	}
});

What you may not know is that you can add these events during the element creation process. Here's how.

The MooTools JavaScript

var a = new Element('a',{
	href: 'https://davidwalsh.name',
	rel: 'lightbox',
	text: 'David Walsh Blog',
	title: 'David Walsh Blog: Best on the Web!',
	'class': 'shoutout',
	styles: {
		color: '#0f0',
		display: 'block'
	},
	events: {
		click: function(e) {
			e.stop();
			console.log('Clicked!');
		},
		mouseenter: function() {
			console.log('You are on top of me!');
		}
	}
});
a.inject($('description'));

Cool, huh?

Recent Features

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

Incredible Demos

  • By
    Add Styles to Console Statements

    I was recently checking out Google Plus because they implement some awesome effects.  I opened the console and same the following message: WARNING! Using this console may allow attackers to impersonate you and steal your information using an attack called Self-XSS. Do not enter or paste code that you...

  • By
    Disable Autocomplete, Autocapitalize, and Autocorrect

    Mobile and desktop browser vendors do their best to help us not look like idiots by providing us autocomplete, autocorrect, and autocapitalize features.  Unfortunately these features can sometimes get in the way;  we don't always want or need the help they provide.  Luckily most browsers allow...

Discussion

  1. I’ll also add that I look at a lot of other users’ MooTools code and see the same adding of events after creation instead of during.

  2. It’s not a real mistake to add the events in that way.

  3. @marcus: Currently I really appreciate David job. His blog has a lot of reader and a lot doesn’t really know mootools in depth. Plus, as he said, usually you don’t remember each of the refinements of the framework. Any article pointing the engine strengths is welcome ;D

  4. jacob

    I was not aware of that. Thanks :D

  5. I’m sure you know but figured I’d mention it for any of the newer guys reading this… you can chain the .inject($('description')) onto the end of the element creation.

  6. olivier

    like ‘events’, you can also set effects with ‘tween’,’morph’,’slide’. You can actually set any of the value of the Element.properties Hash

  7. @Ryan: Yep — wanted to keep the example as simple and “readable/understandable” as possible for a noob.

    @Olivier: I considered adding those too but again, I wanted to keep this very simple. Thank you for mentioning that though!

  8. Jan

    In the beginning I always red your blog but now almost all your post are about MooTools. Why don’t you write about jQuery? There are a lot more jQuery users..

  9. You can also avoid having to create a variable, to hold the instance of the new Element so that it can be injected, by directly injecting it right away.

    new Element('a',{ 
         href: 'http://davidwalsh.name', 
         rel: 'lightbox', 
         text: 'David Walsh Blog', 
         title: 'David Walsh Blog: Best on the Web!', 
         'class': 'shoutout', 
         styles: { 
             color: '#0f0', 
             display: 'block' 
         }, 
         events: { 
             click: function(e) { 
                 e.stop(); 
                 console.log('Clicked!'); 
             }, 
             mouseenter: function() { 
                 console.log('You are on top of me!'); 
             } 
         } 
     }).inject($('description'));
    
  10. Jem

    I definitely dont create my events in the constructors as often as I could either, its nice to be reminded that this option exists from time to time!

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