Reputation: 8971
A couple times now I have wanted to check element sizes as the page loads. I've been doing that using $(document).ready();
, but find that often the properties are null. The same is true if I use $(window).load();
.
To get around this I have been using a bit of a hack, where I recursively recall the function if the element is not set.
Question: Is there a better approach in terms of professionalism?
var makeMusic = {
init: function() {
if ($('#bloc-1').height() == null) {
setTimeout(function() {
makeMusic.init() ########## THIS IS THE HACK ##########
}, 10)
} else {
makeMusic.height = $('#bloc-1').height();
makeMusic.width = $('#bloc-1').width();
}
makeMusic.watchExperience();
},
watchExperience: function() {
//Some stuff
}
}
var Main = {
run: function() {
makeMusic.init();
}
}
$(document).ready(Main.run());
Upvotes: 2
Views: 37
Reputation: 1650
In terms of proffessionalism i think its better to put your code in a namespace like this:
var app = window.app || {};
app.set = {};
app.set.makeMusic = (function(){
// private members
this.height = "";
this.width = "";
var init = function() {
height = $('#bloc-1').height();
width = $('#bloc-1').width();
alert(height + " " + width);
};
//public interface
return {
init: init
};
})(); // self invoked
$(function(){
app.set.makeMusic.init();
});
Upvotes: 1
Reputation: 2479
You do not need a hack at all. The issue here is that Main.run
function is invoked before document.ready()
is fired. You should:
$(document).ready(Main.run);
Instead of
$(document).ready(Main.run());
When you add ()
to the function name interpeter invokes it as soon as the line is reached.
When passing a callback, you should only pass a reference to the function.
Upvotes: 3