Can you have multiple $(document).ready(function(){ ... }); sections?
You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:
http://www.learningjquery.com/2006/09/multiple-document-ready
Try this out:
$(document).ready(function() {
alert('Hello Tom!');
});
$(document).ready(function() {
alert('Hello Jeff!');
});
$(document).ready(function() {
alert('Hello Dexter!');
});
You'll find that it's equivalent to this, note the order of execution:
$(document).ready(function() {
alert('Hello Tom!');
alert('Hello Jeff!');
alert('Hello Dexter!');
});
It's also worth noting that a function defined within one $(document).ready
block cannot be called from another $(document).ready
block, I just ran this test:
$(document).ready(function() {
alert('hello1');
function saySomething() {
alert('something');
}
saySomething();
});
$(document).ready(function() {
alert('hello2');
saySomething();
});
output was:
hello1
something
hello2
You can use multiple. But you can also use multiple functions inside one document.ready as well:
$(document).ready(function() {
// Jquery
$('.hide').hide();
$('.test').each(function() {
$(this).fadeIn();
});
// Reqular JS
function test(word) {
alert(word);
}
test('hello!');
});
Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.