0

Inside an HTML I have a script:

<script src="info.js" type="text/javascript"></script>

Inside info.js there is a function, lets say getInfo(key) which returns info.

How can I call a function located inside info.js from my html, so that I can use this variable inside the whole html document?

w3schools does not explain how to do this

1
  • w3schools isn't really a great source for learning JavaScript. Commented Apr 29, 2014 at 21:11

5 Answers 5

2

Something like this:

var global; // global var

// js code...


// function
function myFunc(){
  global = getInfo(key);
}
Sign up to request clarification or add additional context in comments.

Comments

1

This might help you understand what's going on.

Let's say the code below is located inside info.js

function getSomething(){
  return "something";
}

Now your HTML might look like this

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="info.js" type="text/javascript"></script>
</head>
<body>

    <span id="mySpan"></span>

    <script>
        var myText = getSomething();

        $('#mySpan').text(myText); //this uses jQuery so you'll need to include that
    </script>
</body>
</html>

2 Comments

Thank you. That's the exact explanation I was looking for. I was finding it difficult to understand where do I put all these scripts and where to call the function from.
@FilipLuch You're welcome. This website might be beneficial to you: webdesigndegreecenter.org/learn-to-code
1

If I got you correctly, that you want to use that info in all your html file, here's my answer. Let me know if it helps or if you meant anything else, I'll think accordingly.

<html>
<head>
    <script src="info.js" type="text/javascript"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var info = getInfo(key);
            $('div.myinfo').html(info);
        });
    </script>
</head>
    <div class="myinfo"></div>
</html>

You have the desired information in a javascript var and you can assign it as value to a input/select element or copy it as html to a div/td/p/h1 etc.

Comments

0

Just use it like this:

var info = getInfo(key);

Comments

0

As long as your calling script follows the method in info.js (and assuming the function is not private) it should be accessible in any script

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.