O'Reilly

Create Custom Events in MooTools 1.2

By on  

Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets.

The MooTools JavaScript

/* click - control event */
Element.Events.altClick = {
	base: 'click',
	condition: function(event) {
		return event.alt; // alt key?
	}
};

/* usage */
window.addEvent('domready',function() {
	var ccs = 0, acd = $('alt-click-div');
	acd.addEvent('altClick',function() {
		acd.set('text','You have alt-clicked me ' + (++ccs) + ' times');
	});
});

What's great about creating custom events in MooTools is that you need to give the Element.Events object as little information as you could imagine: a base to listen for the custom event for and a condition property that you return a Boolean value from if the condition matches your desired event.

When would you use alt-click? Maybe in my MooTools ContextMenu plugin? Do you have any custom events you live by?

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

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

Incredible Demos

  • Use Custom Missing Image Graphics Using Dojo

    A few months back I posted an article about how you can use your own “missing image” graphics when an image fails to load using MooTools and jQuery. Here’s how to do the same using Dojo. The HTML We'll delegate the image to display by class...

  • Create Custom Events in MooTools 1.2

    Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets. The MooTools JavaScript What's great about creating custom events in MooTools is...

Discussion

  1. jem

    I use custom events in a lot of the classes i write. more complex tools i tend to break into multiple classes… like a slideshow might have a SlideShowManager class, and then it manages instances of a SlideClass. The Slide class will take the “controller” as an argument in its init function, and i have slides listen to custom events that the controller fires. I’ve found this helps keep the flow of the tool a lot cleaner and leaves less room for weird glitches or unusual logic… The manager might do something like this in a function:

    this.fireEvent(‘onSlideSelect’, [slideId, blah, blah])

    The slides that are listening can identify if they need to respond by comparing their ID to the slideId thats passed.

  2. adamnfish

    I might be missing something obvious but it doesn’t seem to work in OSX.

  3. he’s right, it doesn’t work on OSX david ! :(

  4. Thanks for the update guys. I wonder if it has something to do with Mac’s “option” key. I don’t develop on Macs — I’ll look for a solution though!

  5. adamnfish

    Yeah, OSX doesn’t pass the ctrlKey property of an event ever so if event.control is reading from that directly it won’t work. A cross browser implementation would probably need to listen for the keycode of ctrl and set the event’s ctrlKey property to true if it is down.

    That would mean listening for key presses on the whole document though, so it wouldn’t be worth it unless you really needed the functionality.

    ps. altKey seems to work fine!

  6. @adamnfish: Thanks. I’ve changed to the ALT key and it works perfectly. I’ll research the “control” issue further. Someone metioned that control-click is the same as right-click on a Mac, but I’ve yet to verify.

  7. Element.Events.konami = {
        base: 'keyup',
        condition: function(e){
            $clear(this.retrieve('konami_timeout'));
            var input = this.retrieve('konami_input',[]);
            input.push(e.key);
            if (input.join(',') == "up,up,down,down,left,right,left,right,b,a,enter"){
                this.removeEvents('konami');
                return true;
            }
            this.store('konami_input',input).store('konami_timeout',(function(){this.eliminate('konami_input');}).delay(2000,this));
        }
    };
    
  8. Daniel Steigerwald

    Hi David, you have to check meta key for mac. Another event extension:

    Event.implement({
        uberControlPressed: function() {
            return Browser.Platform.mac ? this.meta : this.control;
        }
    });
  9. Awesome Daniel!

  10. Nice, but ALT+click does not work on Linux LOL! I know, is very hard to write scripts crossbrowser. The problem is not Linux exactly, is because ALT+Click is an event for Drag&Drop the windows on the Gnome Desktop from any part of these. I do not know if this happens too on KDE.

    But, I tested with control key and works fine. Nice tip David, I’m gonna put it on the practice right now.

  11. David, it work now on macOSX with firefox3 and the Alt-Click :)

  12. olivier: Awesome!

  13. Hi David,

    There is a conflict between your alt+click and FlashGet Download Manager.

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

Recently on David Walsh Blog

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...

  • Create Any Type Of Website With These Multi-Purpose Themes

    We have selected what we believe are the very best multipurpose WordPress themes on the market today. Our list contains a number of best sellers, several newcomers that are proving to be highly popular, and a few themes that are ideal for creating the types of...

  • An Introduction to Static Site Generators

    Static site generators seem to have been becoming more and more popular recently, but they’re not one of those ephemeral novelty things that grow in popularity as quickly as they fall into oblivion shortly after. For over a decade, many different projects — 394 of...

  • Automated Tests for Visual Responsive Layouts

    Today it's all about testing. In 2015, many developers knows about TDD and I personally think that testing is one of the key for quality products. But what about testing in a Front-end environment? How do you guys write your tests for a responsive page or...

  • Getting Dicey With Flexbox

    What if you could build complex CSS layouts in minutes? Flexbox is a new CSS layout spec that makes it easy to construct dynamic layouts. With flexbox, vertical centering, same-height columns, reordering, and direction agnosticism are a piece of cake. There's a popular myth floating around that...