If I run the function below before defining it, I will get this error...
Uncaught ReferenceError: openModal is not defined
run then define
$(document).ready( function() { delay(openModal, 2000); delay = function (f, t) { setTimeout(function() { f(); }, t); }; openModal = function () { $('#modal-box').css( { left: $(window).width() / 2 - $('#modal-box').width() / 2, top: $(window).height() / 2 - $('#modal-box').height() / 2 } ); $('#modal-box').show(); $('#modal-mask').show(); }; });
Now if I define the function first and then call it it works...I have a background in PHP so I am used to being able to access functions globally, am I doing something wrong or do all functions have to be defined before they can be used?
$(document).ready( function() { delay = function (f, t) { setTimeout(function() { f(); }, t); }; openModal = function () { $('#modal-box').css( { left: $(window).width() / 2 - $('#modal-box').width() / 2, top: $(window).height() / 2 - $('#modal-box').height() / 2 } ); $('#modal-box').show(); $('#modal-mask').show(); }; delay(openModal, 2000); } );
When you assign a function to a variable, you have to assign it before you can use the variable to access the function.
If you declare the function with regular syntax instead of assigning it to a variable, it is defined when code is parsed, so this works:
$(document).ready( function() { delay(openModal, 2000); function openModal() { $('#modal-box').css( { left: $(window).width() / 2 - $('#modal-box').width() / 2, top: $(window).height() / 2 - $('#modal-box').height() / 2 } ); $('#modal-box').show(); $('#modal-mask').show(); }; });
(Note the difference in scope, though. When you create the variable openModal
implicitly by just using it, it will be created in the global scope and will be available to all code. When you declare a function inside another function, it will only be available inside that function. However, you can make the variable local to the function too, using var openModal = function() {
.)
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