May
6
2010

Mootools Message Class

This Message Class is a simple Mootools plugin that replaces the a standard dialog box like javascripts built in alert method. Now you’ll will be sending a message to the user in style! Read on! It’s quite useful.

Before we get started, this is open source code and, like Mootools itself, it is released under the Open Source MIT Licence. But, please give me credit by leaving the url to this site in the js files. Thanks!

Say Method

Click on this to see.

// Simplest way to use the class...
new Message({
	icon: "okMedium.png",
	title: "Success!",
	message: "You have successfully messaged your user."
}).say();

Tell Method

You can get bossy with the “tell” method of the class by forcing the user to respond. Click on this to see.

// Here I'm creating an instance of the Message Class and storing it the msg variable.
var msg = new Message({
	icon: "cautionMedium.png",
	title: "Watch Out!",
	message: "You just might be a redneck!"
});
// Execute the command!
msg.tell();

Ask Method

You can also ask a question by using the ask method. (See how clever I am? I named the methods after the what they do!) You can also send a callback function to complete a transaction when the user chooses “Yes”. Wow! Think of the power! Get the class to perform a task by sending either a function in the form of a string, or an element that has an assigned click event. When the user clicks “Yes”, the class will fire the function or the click event (which ever you passed in the callback option).

Click on this to see.

new Message({
	icon: "mediumQuestion.png",
	title: "Question!",
	message: "If a woman is yelling at a man and he's not there to hear it, is he still wrong?",
	callback: "saySimple()"
}).ask();

Waiter, Comment and Tip Methods

There are all kinds of things that this bad-boy can do. Click on the following links to marvel at the possibilities!

You can create a waiter using the waiter method.
Click here to dismiss the waiter.

You can create a comment box pop up.

How the heck did I do that? Here’s the code:

document.id('commentLink').addEvent('click', function(e){
	// Just creating an object here so that you can see that it's possible to send one.
	// Imagine the power in that!
	var obj = new Element('div', {
		'id': 'dummy',
		'events': {
			'click': function(){
				sendComment();
				this.destroy();
			}
		}
	});
	new Message({
		icon: "speakMedium.png",
		iconPath: "/2010/images/",
		width: 300,
		fontSize: 14,
		passEvent: e,
		autoDismiss: false,
		title: 'Have a Comment?' ,
		message: '<textarea id="commentText" cols="3" rows="5" class="msgEditable"></textarea>',
		callback: obj
	}).say();
});
var sendComment = function(){
	new Message({
		icon: "okMedium.png",
		iconPath: "/2010/images/",
		title: "Received!",
		message: "We've received your comments, and we'll ...uhhh... get back to you."
	}).say();
}

You can even create a tool tip. Yeah… I know it’s a built-in plugin in Mootools, but I think that this does it better. (I could never get the Mootools tooltip plugin to work the way I wanted.) Besides, I already created this class, so extending it to do tips was simple. Click on these to see the tip method in action:

I’m a tip
…and I’m a tip
…and I’m a tip too!

With the tip method, the HTML is important because we use the rel property in the a tag to pass a title and a message. This way, you can set your tips right in the HTML.

<a href="javascript:" class="tips" rel="Tip!::This is tip #1">I'm a tip</a>
<a href="javascript:" class="tips" rel="Tip!::This is tip #2">...and I'm a tip</a>
<a href="javascript:" class="tips" rel="Tip!::This is tip #3">...and I'm a tip too!</a>

The Javascript:

$$('.tips').addEvent('click', function(e){
	new Message({
		iconPath: '/2010/images/',
		icon: 'mediumQuestion.png',
		passEvent: e,
		callingElement: this
	}).tip();
});

Notice how the tips disappear on mouse rollout. This is achieved by passing the element that called the tip method. Pass this element using the callingElement option in the class’ constructor just like I did above.

Positioning

Just when you thought you’ve seen it all, you get a blast of another cool feature: positioning! That’s right, if you like it on top, you can position the message to align to the top by passing the “top: true” option. If you want it aligned to the left, simply pass the “left: true” option, and voilà… instant positioning! Just the way you like it. See the following:

Do it on the left.

Details

Ok… so the Message class is the bomb! So, what are the details? Here they are:

Constructor:

Message({options});

Options:

callingElement: (element: default to null). You use this option when you need the message to auto hide on the mouse out event. Essential when using the tip method.

callback: (string or element). The function that you want to fire when the user confirms the message by pressing “Yes”. i.e.: “myFunction()”, or just send an element with a click event attached to it.

top: (boolean: defaults to false) Set the message to come out from the top edge of the window. Defaults to the bottom.

left: (boolean: defaults to false) Set the message to the left. Defaults to right.

centered: (boolean: defaults to false) Set the message to the center of the window.

offset: (integer: defaults to 30) Determines the padding to give from the edge of the browser window frame.

width: (mixed: defaults to ‘auto’) The CSS value of your message. Pass a number to change it.

iconPath: (string: defaults to ‘image/icons/’) The path of the icons that you’d like to use.

icon: (string: defaults to null) The file name of your icon image. Note: your icon is expected to be 40 x 40! Can be changed in the CSS.

title: (string: defaults to null) The title of your message.

message: (string: defaults to null) Your message.

delay: (integer: defaults to 0) Delays the display of your message. Integer is interpreted in milliseconds.

autoDismiss: (boolean: defaults to true) The message will dismiss on it’s own. Note: this is shut off automatically when user input is needed.

dismissOnEvent: (boolean: defaults to false) The message will dismiss on the mouseout event. Note: this is used automatically when an event is passed.

isUrgent: (boolean: defaults to false) Use the “urgent” transitioning to get the user’s attention. Note: this is automatically used on the ask and tell methods.

callback: (string: defaults to null) Send a function in the form of a string to be fired on confirmation of an ask method.

passEvent: (event: defaults to null) Passing an event will make the message appear at the your cursor location (offset by 5 px).

tipMode: (boolean: defaults to false) Tip mode is a short-cut that sets the autoDismiss and dismissOnEvent to true.

stack: (boolean: defaults to true) This will stack messages one over (or below) the other message rather than on top of one another (as in a z-index value). **Note that if you over use messages, the stacking goes a little wonky. This is a known issue, and I spent many hours trying to perfect this, but doing so would make this plugin a LOT bigger. Not sure I want to do that. Still experimenting.

fxTransition: (Fx.Transition: defaults to null) Set your own transition. The default transition will simply fade in. * fxDuration: (mixed: defaults to ‘normal’) Set the transition duration. Intergers are interpreted in milliseconds.

fxUrgentTransition: (Fx.Transition object: defaults to Fx.Transitions.Bounce.easeOut) Set your own urgent transition

fxOutTransition: (Fx.Transition object: defaults to null) Set the out transition. The default will simply fade out.

fxOutDuration: (mixed: defaults to ‘normal’) Set the transition duration. Intergers are interpreted in milliseconds.

Methods

Note:

* All options can be passed in the constructor! Some can also be passed in the method.

* When isUrgent is on, a “Yes”, “No” or “Ok” confirmation link is added to dismiss the message.

Say

Syntax:
myMessage. say(title, message, icon, isUrgent, callback);

Options:
- title (string: required) The title of your message.
- message (string: required) Your message.
- icon (string: optional) The image icon that you’d like to use in the message. Note: your icon is expected to be 40 x 40! Can be changed in the CSS.
- isUrgent (boolean: optional) Setting it to true will make the message use the Fx.Transition.Bounce.easeOut effect and in the centered position. This is to get the user’s attention.
- callback (string: optional) Sent a function witten in the form of a string to use as a way to fire another function upon a “Yes” click.

Ask

Syntax:
myMessage.ask(title, message, callback, icon, isUrgent);

Options: they are the same as the say method except that the callback is required (or rather expected) and isUrgent is true by default. “Yes” and “No” links will be added to dismiss the message. A click on the “Yes” link will fire the callback function.

Tell

Syntax:
myMessage.tell(title, message, icon, isUrgent);

Options: they are the same as the say method except that isUrgent is boolean and is true by default. An “OK” link will be added to dismiss the message.

Waiter

Syntax:
myMessage.waiter(title, message, icon, isCentered);

Options: They are the same as the say method except that isCentered is boolean and is true by default.

Tip

Syntax:
myMessage.Tip(title, message, icon);

Options: they are the same as the say method.

Events:

onComplete: Fires when the hide message transition is complete.

onShow: Fires when the message shows. Specifically, it will fire when the show transition is fully complete.

Icon Files

Do you want the original Photoshop file that I used to make the icons? Sure! No problemo!

Message Class Icons PSD
Message Class Icons PSD
customIconsLarge.psd
Version: 1
307.9 KiB
399 Downloads
Details...

Requirements and Other Notes

This class requires the Mootools Javascript Framework. I developed it on 1.2.4, and it was updated to be compatible with 1.4+, and it plays nice with JQuery. It’s dependent upon these plugins:

  • Element.Position
  • Element.Measure
  • Element.Shortcuts
  • Chain.Wait
  • Array.Extras

(I hope I didn’t forget any… and if I did, please message me at beaudoin.jason@gmail.com!).

I tested it on IE 7 +, Firefox, Safari and Google Chrome. I don’t support IE6 because nobody should be using that browser. (Friends don’t let friends use IE6. Remember that!) Also, I use CSS 3 in this example. If you’re viewing this in IE 8 or lower, you’re not going to see the CSS 3 support.

Speaking of CSS, you can find the one I used here. But, it’s also included in the package download file, also found at the bottom of this page in the footer.

Message Class Package
Message Class Package
MessageClass.zip
Version: 2.3
57.1 KiB
118 Downloads
Details...
0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

No related posts.

About the Author: Jason Beaudoin

I’m a web developer from Ottawa, Ontario, Canada. My specialty is in JavaScript frameworks, and my current favorite is Mootools. I work for the Canadian army as a web developer, and I have a few other projects on the side that keep me busy including this blog.

54 Comments + Add Comment

  • Opera understand the border-radius property (without vendor specific identifier), but that’s missing from the css file, please include it, thanks.

  • Sorry, I’m forgot the box shadow in the previous comment…

  • awesome…any jQuery for it? :D

  • Baldric… got it! Updated the CSS as requested. Good catch.

  • hi
    Love the class.
    Just wondering where did you find the icons you use.

    And why do the callback has to be a string?

  • @Andreas: It doesn’t have to be a string. It can be a string or an object. It’s your choice. If you pass an object, it will fire that object’s on click event (provided that you set one up for it). If you believe that there’s a better way of doing it, let me know what you’re thinking and I’ll get on it. :D

    The icons… I made them myself. Maybe I should put the PSD up? I think I will.

  • @Jason Beaudoin I sometime like writing my callbacks like :

    callback:function(){
    //do stuff here
    }

    So I fixed like this.

    executeCallback: function(){
    if($type(this.options.callback) == 'element')
    this.options.callback.fireEvent('click');
    else if ($type(this.options.callback)=='function')
    this.options.callback.run();
    else
    eval(this.options.callback);
    },

    The icons are great. Was just wondering because i was looking for an error icon to match.

  • @Andreas: Cool! I’ve added your code to mine. Thanks! I’ll give you credit in the code (and where ever I can actually).

    You’ll find an error icon in the PSD which is now available for download.

  • Thanks for the PSD.

    Glad to help.

  • Hi,
    thanks for this lovely Class. I just wanted to clarify how to use the callback options within another class environment:

    ...,
    removeDo: function(item) {
    // really remove the item
    item.remove();
    },
    removeSth: function(item) {
    var a = new Element('a');
    a.addEvent('click', function(){this.removeDo(item)}.bind(this));

    new Message({
    icon: "mediumQuestion.png",
    title: "Drop this node",
    message: "Are you sure you really want to drop this node ?",
    callback: a
    }).ask();
    }

    Clicking “Yes” no fires removeDo in the same class. Pretty handy when you have several classes.
    Cheers,
    Jan

  • First of all … great class, saved me many hours.

    Furthermore, I customized and modified your class a bit more:
    - concerning the comment links, I added the titles of the send and cancel links to the options (like yes/no).
    - apropos comment, I let also check for “input”, as I needed this type of dialog to be a prompt for entering an email address:
    var isComment = this.options.message.indexOf('textarea') > -1
    || this.options.message.indexOf('input') > -1;

    - finally I needed the value of this field, I saw no passing value to the function and I cannot pass an event, that why I modified the executeCallback:

    executeCallback: function(){
    var formValue = null;
    var inputField = this.box.getElement('input');
    var textArea = this.box.getElement('textarea');
    if(inputField || textArea) {
    formValue = (inputField ? inputField.get("value") :
    (textArea ? textArea.get("text") : null));
    }

    // Determine if the callback is an object, function or a string to evaluate. It is expected that the object will have a click event.
    if($type(this.options.callback) == 'element') this.options.callback.fireEvent('click', formValue);
    else if ($type(this.options.callback)=='function') this.options.callback.run(formValue);
    else eval(this.options.callback);
    },

    Best Regards,
    Tom-Steve

  • Interesting script. I expected the first couple of examples to be in a fixed position. Maybe there should be an option added in?

    • I could certainly consider this when I work on it some more. The thought had crossed my mind, but when I implemented the option to pass an event object (as in my tip examples), I wasn’t sure that exact positioning would be widely used. Definitely a good suggestion.

  • Hey man,

    Nice class, but I wanna ask you, is possible have a modal for you class?
    Is hard to implement?

    Thanks,

    Best regards,
    Leonardo Lima

    • Absolutely. The waiter method does this and the example is on this page. All that you have to do is pass a null value to the Title and Message options, and set the width smaller.. then you’d have your modal. Not sure if this is what you’re looking for? Let me know if you need help and I’ll write it up for you.

      • Hi,

        The problem I was facing was that when I fired a warning message was displayed just the window with the message, and background elements were not blocked with a modal. And I like that when there was a warning he activates the modal.

  • Hi,

    Nice plugin… but I wanna ask, is possible for this plugin have a modal blocking the back window…

  • A fantastic class. Well done! First a correction on dependancies. You need to add Chain.Wait to your list.

    OK now the requests… Can you stack em? Instead of laying them on top of each other place them above or below the previous one. And if the user hovers over one with the mouse it should not disappear until the mouse leaves.

    Cheers!

    • Hi Adam! Thanks for the corrections. I’ll add them ASAP!

      Stacking is a GREAT idea! Why didn’t I think of that?! When I get a chance, I’m going to have a look to see if I can implement that change!

      • Thanks, that’d be great! I look forward to it as it really is a great little bit of pro coding!

      • Stacking would be really fantastic. Thanks for this beautiful class!

      • I am thinking to use this class for a professional project. Stacking will be really appreciated. You can take inspiration from Notimoo:

        http://www.paquitosoft.com/?page_id=53

        Thanks a lot for share your code

  • Would love to see this with the new updates from the comments! Would like to use.

  • Great … no more words. In my page I’ve put “Don’t use IExplorer 6″

    And Jason Beaudoin, you missed a plugin: Chain.Wait

    • Ok… added Chain.Wait to the instructions below. Thanks!

      I also added the stack option (which is set to true by default).

      • Oh my god, It’s amazing … stacking is great.

        The best library …

        Thanks Jason Beaudoin and I’m gonna update the lib on my site …

  • it not work!!!

    Try

    var saySimple = function(){
    new Message({
    iconPath: “images/”,
    icon: “okMedium.png”,
    title: “Success!”,
    message: “You have successfully messaged your user.”
    }).say();
    }

    Click on this to see.

    i try evrrythink but not work!!!

    in firebug i have this error:
    c.getComputedSize is not a function
    [Break on this error] var Message=new Class({Implements:[Opt…oxSize.y;this.fxOut.start(“top”,b)}});

    • Gimox: That’s because you are missing a dependency: Element.Measure

  • ok.
    i read the source of this page and i see mootools-more_src.js.

    i download and add to my page and now work.
    thanks
    is very beautifull effects

    • an other help.

      about tips.

      $$('.tips').addEvent('click', function(e){
      new Message({
      iconPath: '/b2b/tema/default/img/',
      icon: 'debug.png',
      passEvent: e,
      callingElement: this
      }).tip();
      });

      ...and I'm a tip

      i use a html5 initialization and NOT WORK.
      can you help me?

      • I’ll need to see your page to help you diagnose the problem you’re having. Send me an email with a link to your page, and I’ll see what I can do.

  • thanks a lot for the post. good work

  • hello, first tnks for this class i think is great.
    and second, have a little issue whit this.
    i have a loop that create messages from array, the messages appear one over the other message rather than on top of one another.

    Activities.each(function(item){
    new Message({
    icon: ‘okMedium.png’,
    dismissOnEvent: false,
    autoDismiss: true,
    title: ‘Next activity!’,
    message: item.task_name
    }).say();
    }

    how can i put messages top of one another ??

    • It sounds like you may be using an old version of my class because I’ve updated it since so that it can stack one over the other, just like you want. If you’re using Mootools 1.3, you’ll be able to download the latest version and use that one. Regardless, I’m quite sure that I updated it before implementing a new version for Mootools 1.3.

      • hello, thanks for the quick response.
        this is what I am using in my code.

        mootools-core-1.3-full-compat-yc.js
        mootools-more.js
        message.js v2.1

        i just download and use the new version of message.js (v2.1), and I keep getting same issue

        • Hummm… If you send me a link, I’ll try to diagnose the problem. You can also try and pull my code from this source: http://www.coldfiredesigns.com/2010/?p=120… and you’ll be able to see the code I’m using. The stacking works because I’m using it on this site and in that example.

          • hi, and sorry for the reply so late.
            Here are the link with an example of code that use.

            http://neurona-infnit.com/test/alerts.php
            There must be 2 alerts, but the messages appear one over the other.

            I am testing whether a delay between messages can work.

            thanks in advance.

          • Hi Alan: Instead of doing what you did on this test page, simply create a link that will call a new simple “say” message. This will allow the user to click on it as many times as they want and you should see the messages stack.

  • I love your Class, your code makes me wet!

  • I almost started with my own message class but this is really great! Thanks for publishing such a detailed class! I’ll start implement it directly!

  • wonderful article, it seems absolutely perfect

  • Realy great class. Thank you for your work and willingness to share it :) And it works perfectly :)
    But I also have a question – does this class work if site is also using “jquery-1.6.2″? Because If I include jquery in my site it seems to stop working and if I remove the jquery – it works again.

    • I made a half-hearted effort to make it play nice with other frameworks, but to be honest, I didn’t start off with that mind set, and I never tested it against jQuery. But this class SHOULD play nice, and I’m going to take some time this week to fix it so that it does. I’m glad you brought it up.

  • Great plugin!
    By the way you have two semi-columns missing in the “Waiter, Comment and Tip Methods” javascript block and Chrome does not like this ;-)

    • Thanks! Can you tell me which lines exactly?

      • Adding a semi-colon at the end of this line:
        var waiterSimple = function(){msg.waiter();}
        should solve the problem…

        • Ahhh… you meant on the website itself. I thought you meant the MessageClass code. Ok! I’ll change that. Thanks!

          –Edit: FIXED!—

  • Hi again Jason,
    Like Leonado above, I am wondering how I could create a modal pop-up with your plugin. Do you think it’s possible and how?
    NB : By modal, I mean a way to prohibit the visitor from interacting with the main window until he/she has closed the pop-up. In general, the main window is also grayed out to force the visitor to focuss on the pop-up window.

  • Great class. Absolutely awesome. Been hunting for one like this for aaages.

    Just a heads up tho. In the header of message_src.js you mention the dependencies in mootools more.

    You can add ‘Array.Extras’ in there too.

  • Here’s another vote for a modal option as Fly06. Great class.

  • Great art.

    To run this under core:mootools-core-1.4.4-full-nocompat, more:1.4.0.1
    we should add $chk and $defined, and add Hash component into ‘more’ lib.

    this.$chk = function(obj){
    return !!(obj || obj === 0);
    };
    this.$defined = function(obj){
    return (obj != null);
    };

  • I am looking for the modal option too. For example, If I press a cancel button, I’d like to fire the pop-up which would request where I was sure I wanted to cancel. The page would wait until yes or no is pressed. If no, it should return a false, else a true

  • I’m trying the ‘comment’ method … but how you I read the the text, that is typed in the comment box so I can send it to the server?

    • Hi Allan:

      I’m looking into the problem with the comment feature of the Message Class. I assumed that the comment area would exist in the DOM, but I tested it out today, and it seems that it doesn’t. Once I find a solution, I’ll let you know.

Leave a comment

Ads keep me running!