Daniel Cheung
Daniel Cheung

Reputation: 4839

Jquery - Script Imported But Functions "Not Defined"

My HTML:

<script type="text/javascript" src="js/myjs.js"></script>
<script>
...
$("#enviornment").hide().delay(1200).css({'display':'block', 'opacity':'0'}).animate({'opacity':'1'}, 300, function() {
    $("#main").css("display", "none");
    appearWindow($(".window.q"));
...
</script>

myjs.js contains:

if ("undefined" == typeof jQuery)throw new Error("Nviornment requires jQuery");
$(function() { 
    ...
    function appearWindow(target) {
        changezindex(target);
        target.hide().css({'display':'block', 'opacity':'0'}).animate({'opacity':'1'}, 300)
        target.find(".help").css({'display':'block', 'opacity':'0', 'right':'-40px', 'position':'absolute', 'width':'100%'}).animate({'opacity':'1','right':'0px'}, 580);
    }
    ...
})

The code ran fine before I exported some code into a .js file. But now appearwindow doesn't run, and the console prints ReferenceError: appearWindow is not defined

Upvotes: 1

Views: 887

Answers (2)

AGupta
AGupta

Reputation: 5734

Since you have added your function under Anonymous function hence its scope will not be available outside. You can do it in following way:

if ("undefined" == typeof jQuery)throw new Error("Nviornment requires jQuery");
$(function() { 
    ...
    window.appearWindow = function(target) {
        changezindex(target);
        target.hide().css({'display':'block', 'opacity':'0'}).animate({'opacity':'1'}, 300)
        target.find(".help").css({'display':'block', 'opacity':'0', 'right':'-40px', 'position':'absolute', 'width':'100%'}).animate({'opacity':'1','right':'0px'}, 580);
    }
    ...
})

and on other side you can use it:

$("#enviornment").hide().delay(1200).css({'display':'block', 'opacity':'0'}).animate({'opacity':'1'}, 300, function() {
$("#main").css("display", "none");  
// either by
appearWindow($(".window.q"));  
// or by this  
window.appearWindow($(".window.q"))

Upvotes: 3

jeremy castelli
jeremy castelli

Reputation: 1260

I think it's a scope issue.

Where is located your function appearWindow(target){.... ?

is it inside a global anonymous function like

(function(){
    ....
    appearWindow(target){
        ....
    }
    ....
})()

if so, you cannot access your function from outside

Upvotes: 1

Related Questions