MooTools Tip: Adding Events During Element Creation

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?