How to have a box default to hidden and then fade it in later

Fade is just a Tween. And Tween simple animates one CSS property from one value to another. That’s it. Also, you can’t have your code run until the dom is ready (when the page finishes loading enough). None of your javascript rules can effect anything until after the user has already seen the page. So, you have to hide your box yourself using CSS. There are a million ways to do that, but I recommend having a ‘hide’ class.


Simple: Use a hide class

Add this rule to your CSS somewhere:

.hide{ display:none; }

Then, manually apply it to all the HTML elements that you want to be hidden by default:

<div class="alert hide">Warning Mr Robinson!</div>
<div class="confirm hide">Are you sure you want to do that?</div>
<div class="info hide">Um... Your arm is missing.</div>

Next, add some simple mootools Javascript to setup your elements to be faded later on:

window.addEvent('domready',function(){

	$$('.hide').fade('hide').removeClass('hide');

});

Finally, you’ll need something to make those things fade back in somehow.

$$('.show-alert').addEvent('click',function(e){ $$('.alert')[0].fade('in'); e.stop; });
Note: This is just a crappy example, ideally you'd write MUCH better code than this. Use a MooTools Class and instantiate it onDomready, etc...

Advanced: Use semantic CSS rules

Don’t like the idea of littering meaningless classes around your document? Well, the best option is to do something a bit more complex…

Use a loading class for your body tag

Add the classname loading to your body tag. Then in your CSS you can set multiple rules for how your document should look as it’s loading. Then, once your javascript has all fired, simply remove the loading class to disable all those CSS rules.

With the loading class you can use verbose semantic rules such as:

body.loading div.alert,
body.loading div.confirm,
body.loading div.info{
	display:none
}

Use a MooTools Class to write a reusable widget

This is a basic example of how you should approach this sort of thing. Now that you have a simple MooTools Class all set up, it’s easy to go back and add more functionality without having to recode anything.

var DialogWidget = new Class({

	initialize: function(element, eventName){
		this.eventName = eventName||element;
		this.element = $(element);

		this.element.fade('hide')
			.getElement('.closer').addEvent('click', this.hide.bind(this) );
		window.addEvent(this.eventName, this.alert.bind(this));

		this.init_buttons();
	},

	init_buttons: function(){
		$$('.show-' + this.eventName).addEvent('click',function(e){
			window.fireEvent(this.eventName, e.target.get('title') );
			e.stop();
		}.bind(this));
	},

	show: function(message){
		this.element.fade('in').set('text',message);
	},

	hide: function(){
		this.element.fade('out');
	}
});

window.addEvent('domready',function(){

	new DialogWidget('alert');
	new DialogWidget('confirm');

		$(document.body).removeClass('loading');
});