Is it correct to create functions inside of
$(document).ready(function() {
like so:
$(document).ready(function() { function callMe() { } });
The function inside of the .ready()
does not have to call before DOM is ready and event inside of the ready()
is triggered.
Just to clarify a little bit - here's the code which would illustrate the problem:
$(function() { var ind = 0; // some event is executed and changes the value of the ind // another event which affects the ind variable // and another one - after this event we call our function // there's another event - and we call our function again
The function which I need to call needs the updated value of the ind
variable - which I guess I could pass as a parameter, but is there a better way of doing it?
Also - another important thing is that the function()
in question can also change the value of the ind
variable - for instance incrementing it (ind++
).
Yes, you can do that, it's just a matter of scope. If you only need to access callMe() from within $(document). ready(function() { }) , then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.
$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
Yes, you can.
jQuery Document Ready Example ready(function() { //DOM manipulation code }); You call jQuery's $ function, passing to it the document object. The $ function returns an enhanced version of the document object. This enhanced object has a ready() function you can call, to which you pass a JavaScript function.
Yes, you can do that, it's just a matter of scope.
If you only need to access callMe()
from within $(document).ready(function() { })
, then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.
If you need to use the callMe()
function outside of document ready though, you need to define the callMe()
function outside of that context.
function callMe() { // Do Something } $(document).ready(function() { callMe(); });
Based on your clarification, you have two options:
1) DECLARE variable outside of ready()
, but then define variable inside of ready()
:
var someVariable; function callMe() { someVariable++; alert(someVariable); } $(document).ready(function() { someVariable = 3; callMe(); // Should display '4' });
2) Within ready()
, define variables using window.yourVariable = 'whatever';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With