I am quite new to JavaScript. I am trying to set equal heights to some elements. I managed to do everything except moving the function outside the “addEvent” declaration.
In other words, this code works:
window.addEvent('domready', function() {
var elements = $$( 'div#leftcolumn div.module_menu' );
if( elements && elements.length > 1 ) {
var heights = [];
elements.each( function( el ) {
heights.push( el.getStyle('height').toInt() );
});
maxHeight = Math.max.apply( Math, heights ) + "px";
elements.each( function( el ) {
el.setStyle('height', maxHeight );
});
delete(heights);
}
}
);
while this code does NOT work:
function matchHeight( selector ) {
var elements = $$( selector );
if( elements && elements.length > 1 ) {
var heights = [];
elements.each( function( el ) {
heights.push( el.getStyle('height').toInt() );
});
maxHeight = Math.max.apply( Math, heights ) + "px";
elements.each( function( el ) {
el.setStyle('height', maxHeight );
});
delete(heights);
}
}
window.addEvent( 'domready', matchHeight( 'div#leftcolumn div.module_menu' ) );
I already test with simpler functions and it works, like e.g:
window.addEvent('domready', function() { alert('test'); } )
is equivalent to
function giveMessage() { alert('test'); }
window.addEvent( 'domready', giveMessage())
why is that?
It’s because you need to remove the parenthesis; a function is an object, and you need to pass the function, not its return value. So, for your first example, you should have:
Instead. For your second example, it’s:
Again, you pass the object
giveMessage, not the result obtained after invoking it.