jQuery - calling function from other script


#1

I've got two scripts that are loaded from external files. The first script needs to call a function from the other, but I don't know how to make it happen. Right now I just get an error that the function doesn't exist.

// This script actually loads from an external file
$(document).ready(function(){
	$('button').click(function(){
		whatever();
	});
});

// This script loads from another external file
$(document).ready(function(){
	function whatever(){
		alert('yes');
	}
})

;

How can I do what I am trying to do?


#2

The 'whatever' function is inside a different scope. In JavaScript a function defines the scope of the code it contains, so if you want to share it you need to define it in a location that your other code can see.

You also don't need to define functions inside the document ready function, you could just define outside of the ready() callback. Eg,

$(document).ready(function(){
    $('button').click(function(){
        whatever();
    });
});

// This script loads from another external file
function whatever()
{
     alert('yes');
}
$(document).ready(function(){
    // run something else
});

I think in your example by defining it inside the callback of .ready() you'd have a chicken and egg thing going, you could never be sure the function would be defined when you actually want to use it, so try defining your functions first outside of .ready().


#3

Thanks for answering. I ended up doing this:

// This script actually loads from an external file
$(document).ready(function(){
	$('button').click(function(){
		$.whatever();
	});
});

// This script loads from another external file
$(document).ready(function(){
	$.whatever = function(){
		alert('yes');
	}
});

It works, but I think your solution that places the function outside of document ready function may be best.


#4

Personally i prefer using namespace objects inside an anonymous function then declare all the properties and methods inside of it, so instead of extending off the object half way through the code you declare it once and then add it to the window scope.

(function($) {
    
    var namespace;
    
    namespace = {
        something : function() {
            alert('hello there!');
        },
        bodyInfo : function() {
            alert($('body').attr('id'));
        }
    };
    
    window.ns = namespace;
    
})(this.jQuery);

$(function() {
    ns.something();
    ns.bodyInfo();
});

Also using 2 DOM.ready() methods is redundant, you only ever need one for the page unless you have multiple sets of code that need to be independent of each other.


#5

Yes, the 2 DOM.ready() methods are from external scripts that are independent. I was just showing them here because that's the way they would be if combined.

Thanks for the example, although I had to stare at it for a few minutes to figure out how it was working.