0

I have the following code:

(function($) {
  "use strict";

  $(function() {
    // jQuery code here, eg:
    $('body').css('padding-top', $('.nav').height());
    // I want to call that func here...
  });

}(jQuery));

And custom function:

function xyz(a,b) {
  // do something with "a" and "b"
}

Where should I place my custom function? Before (function($) {, before $(function() {, or inside $(function() {});?

3
  • 4
    depends on where you are going to use xyz Commented Mar 17, 2014 at 14:52
  • What do you want to put? Declaration or Defination? Commented Mar 17, 2014 at 14:53
  • I want to use it inside $(function() { // I want to call that func here... }); Commented Mar 17, 2014 at 14:53

2 Answers 2

2

The difference is the scope.

Location              :  Scope
----------------------+--------------------------------------------------------
before (function($) { :  in global scope, easy to call & modify from everywhere 
before $(function() { :  in "source module" scope / jQuery closure
inside $(function() { :  in "$(function" scope 

So that choice gives you the means to organize the access to your code. In most cases you want to hide stuff to prevent unintended interactions, but in some cases (e.g. log function), you want to have access from everywhere in your web application.

If you do not need to call xyz() from outside $(function, keep it inside. If you do just need to call it within the module, keep it inside ( .. (jQuery)). If you need to call it from everywhere keep it outside in global scope.

Sign up to request clarification or add additional context in comments.

Comments

1

Since you want to call the function inside the ready handler, declare it inside it

jQuery(function ($) {
    "use strict";

    // jQuery code here, eg:
    $('body').css('padding-top', $('.nav').height());
    // I want to call that func here...
    xyz();

    function xyz(a, b) {
        // do something with "a" and "b"
    }
});

But if you want to access xyz from outside the scope of the dom ready handler you will have to declare it outside the scope of the dom ready handler. Now the method is local to the dom ready handler and thus accessible only inside it.

Also as shown above you can shorten the use of IIFE and dom ready handler as shown above

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.