masber
masber

Reputation: 3067

call javascript function located in main html from external js file

sorry this problem might be resolved already, but I have not been able to find the answer.

I basically have 2 files:

form.html code:

<!DOCTYPE html>
<html>
<head>
<script src=".../fileA.js"></script>
<title>BACKUP MONITOR</title>
<script>
    function getEvents()
    {
        alert("getEvents");
    }

    alert("in HTML");
</script>
</head>
<body>
</body>
</html>

fileA.js code:

alert("in fileA");
getEvents();

Question 1:

I can't call getEvents() from fileA.js. Is there any way to do this?

Question 2:

Could I create a new Window from form.html and call getEvents() from there? please see code below:

New form.html code:

<!DOCTYPE html>
<html>
<head>
    <title>BACKUP MONITOR</title>
    <script>
        function getEvents()
        {
            alert("getEvents");
        }

        alert("in HTML");

        var w = window.open();

        var s = w.document.createElement("script");
        s.type = 'text/javascript';
        s.src = ".../fileA.js";
        w.document.body.appendChild(s);

        w.alert("New Window");
    </script>
</head>
<body>
</body>
</html>

thank you very much

Upvotes: 0

Views: 164

Answers (2)

rts
rts

Reputation: 191

Change the order in which your scripts load. Your external script .../fileA.js is loading before the getEvents function is defined in your embedded script. The call to getEvents in your external script can't succeed if the function doesn't exist yet.

form.html code:

<!DOCTYPE html>
<html>
<head>
<title>BACKUP MONITOR</title>
<script>
    function getEvents()
    {
        alert("getEvents");
    }

    alert("in HTML");
</script>
<script src=".../fileA.js"></script>
</head>
<body>
</body>
</html>

Upvotes: 1

user3296575
user3296575

Reputation: 21

Your code should be like this

<!DOCTYPE html>
<html>
<head>
<title>BACKUP MONITOR</title>
<script>
function getEvents()
{
    alert("getEvents");
}

alert("1");
var eventArray = getEventArray();

var w = window.open();
alert("2");
</script>
<script src=".../fileA.js"></script>
</head>
<body>
</body>
</html>

Upvotes: 0

Related Questions