Bastian
Bastian

Reputation: 5855

How to move a javascript function from an html file to a js file and call it from the html?

Javascript newbie here. I have a javascript function that works nested in an html file, I import an external library abaaso, then declare the function and then call it:

<!DOCTYPE html>
<html>
<head>
    <title>title</title>
    <script src="abaaso.js"></script>
</head>

<body>

<script>
    var baseurl = "https://example.com";
    var baseapi = baseurl + "/api/v1/";
    var api_username = "user";
    var api_key = "key";
    var credentials = "?api_username=" + api_username + "&api_key=" + api_key;
    var rawdata = {};

    (function ($$) {

        /* login */
    login = function(username, password) {
    var calledUrl = baseapi + "user/login/" + credentials;
    calledUrl.post(
        function (content) {
            /*console.log("success" + JSON.stringify(content, null, 4));*/
        },
        function (e) {
            console.log("it failed! -> " + e);
        },
        {
                "username": username,
                "password": password

        },
        {"Accept" : "application/json"}
    );
    }

})(abaaso);

login('[email protected]', 'passwd');

</script>
</body>
</html>

I want to put it in an external .js file and import it and only use the call to the function login('[email protected]', 'passwd');. I don't want to import abaaso from the html file but from the new .js.

How can I do that? Is there a particular structure to respect? Do I need to create a global function to the js file?

Upvotes: 0

Views: 189

Answers (1)

&#201;tienne Miret
&#201;tienne Miret

Reputation: 6650

I don't want to import abaaso from the html file but from the new .js.

You can't do that. However, you can import both abaaso and the new .js:

<head>
  <title>title</title>
  <script src="abaaso.js"></script>
  <script src="new.js"></script>
</head>

Upvotes: 1

Related Questions