Accessing javascript functions defined in different files

Mike2012 picture Mike2012 · Apr 4, 2011 · Viewed 9.7k times · Source

I am having two seemingly related problems accessing javascript function defined in different places. The first problem I am having is calling function I have defined from the console of firgbug or safari. I defined a function called getRed the looks like this:

    function getRed(row, col)
    {
           // do something stuff and return the red value as a float
    }

I would like to be able to test this function from the console but every time I try and call getRed(1,1); for example, I get an error like this: ReferenceError: getRed is not defined

Do I need to make a special call to define the namespace? I define this function in a javascript file called drawing.js which is define very early in my html page.

The other problem I am having is calling a function defined in that same drawing.js file from the onChange: method of my dojo color palette. Here is the code for the color palette:

<script type="text/javascript" src="drawing.js"></script>
 //the method colorChange is inside drawing.js which is defined before the dojo 
 //color palette
 <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="parseOnLoad: true">
</script>
<script type="text/javascript">
        dojo.require("dojox.widget.ColorPicker");
        dojo.addOnLoad(function() {
            var c = new dojox.widget.ColorPicker({
                onChange: function(val)
                {
                    console.log("BEFORE");
                    colorChange(val);
                    console.log("AFTER");
                }
            },
            "picker1");
        });
    </script>

Here is the definition of changeColor inside the file drawing.js:

    function colorChange(val)
{
    console("colorChange!");
}

Every time I click on the color palette I get the following error: ReferenceError: colorChange is not defined.

I am very new to javascript and I am sure that these two issue have a very similar and easy solution but I have not been able to find the answer online. Can anyone help me out?

I am pretty sure the script is being loaded as this screen shot shows: enter image description here

Answer

James An picture James An · Apr 4, 2011

Console is in the same global scope as your page. Since getRed() and colorChange() are both defined in drawing.js and neither can be found in the global scope, I suspect drawing.js is not being properly included.

To check that drawing.js is actually included (i.e. and you have the file path correct), go to Firebug's Script tab. It'll list all scripts included on the current page.