View Full Version : How to make functions that apply to all instances of a class?

05-05-2007, 08:10 PM
Currently, I have three sub-menus on my page, all of which are defined in the CSS like so (just the numbers differ):

#subMenu1 {
width: 890px;
height: 25px;
background-color: #50e0d4;}

I am also using mootools, specifically the slider module (www.mootools.net).
To make one menu slide in, and the others slide out, I have done this in the HTML:

<a href="#" onclick="getMenu1()">Menu 1!</a>
<script>var Slider1 = new Fx.Slide('subMenu1', {duration: 500});
var Slider2 = new Fx.Slide('subMenu2', {duration: 500});
var Slider3 = new Fx.Slide('subMenu3', {duration: 500});</script>

and this in the .js file:

function getMenu1() {
setTimeout("Slider1.slideIn()", 600);
return false;

I want to cut down on the code, but I dont know how. A friend of mine said to make a generic class and use $$('.mysubmenuclass') to create a generic slider function, but i have NO idea how to do that. Help?

05-06-2007, 12:20 AM
Am I correct in thinking MooTools is built on top of Prototype? If not then the following might need some changes, otherwise it will do what you want:

var Behaviour = {
rulesets: [],
add: function(rules) {
go: function() {
Behaviour.rulesets.each(function(ruleset) {
$H(ruleset).each(function(pair) {
$$(pair.key).each(function(node) {

it allows you to specify, in a similar way to CSS for styles, 'behaviour' to be applied to elements based on a selector.
In your example, it would make sense to have some kind of global 'store' for sliders, makes it a bit more flexible should you, for example, add or remove menus in the future, something like:

var SliderStore = [];

var rules = {
'.menu': function(element) {
SliderStore.push(new Fx.Slide(element,{duration:500});
element.observe('click',function(e) {
Event.stop(e); //to stop the default click-behaviour
SliderStore.each(function(slider) {
if(slider.element!=this) { //if it's not the slider attached to this particular element, then get rid of it, the .element property is a guess...but probably available?
else {
setTimeout(function() { slider.slideIn(); },600);


Event.observe('window','load',function() {

If these sliders are the only things you're using, then what I've given might be over-kill, but it makes javascript event-handling quite a lot tidier. If I'm wrong about MooTools and Prototype, then the above will probably not work at all...