Separating jquery functions across files?

I have several functions that use jquery that are called on different pages. I am wondering if it is possible to define these functions in one file and then call them in different files that are included after the initial file.

Here's an example:

## default.js
$(function() {
    // jquery specific functions here...
    function showLoader(update_area) {
        update_area.ajaxStart(function() {
            update_area.show();
            $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
        });
    }   
});

## other_file.js (included after default.js)
update_area = $('#someDiv');
showLoader(update_area);

      

When I do this, firebug gives me "showLoader" not defined. I'm guessing because of the scope of $ (function () {}); which contains jQuery specific functions. If this case, however, does not mean that I will need to have the same code defining functions in every js file I call them on?

How can I separate these things properly?

Thank!

+2


source to share


4 answers


You don't need to point the definition showLoader

to $(function(){})

, but a call showLoader

like:

## default.js

function showLoader(update_area) {
    update_area.ajaxStart(function() {
        update_area.show();
        $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
    });
}

## other_file.js
$(function(){
    update_area = $('#someDiv');
    showLoader(update_area);
});

      



$(function(){some_code;})

is a jQuery shortcut . It tells jQuery to run this code when the document has finished loading.

+5


source


It might be better to write a plugin:



// default.js
$.fn.showLoader = function() {
    this.ajaxStart(function() {
        this.show();
        $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
    });
};


// other_file.js
$(function() {
    $('#someDiv').showLoader();
});

      

+4


source


The problem is not that you have multiple files, but javascript has a function scope, which means that if you define something (including another function, as with showLoading) inside a function, it will only be available inside that function.

function callMe() {
    var foo = 'bar';
    foo; // is 'bar'
}

foo; // is undefined


function callMe() {
    function foo() {}
    foo; // is a function
}
foo; // undefined

      

+2


source


You need to resolve the dependencies yourself if I'm not mistaken. No boot device script in jquery?

0


source







All Articles