2

Is it possible to call a javascript function from an .html file while in a .js file? For example, I have this in my foo.js:

$(document).ready(function() {
    fn(); 
})

And I want to call fn() which is in my index.html:

<script type="text/javascript" src="js/foo.js"></script>
<script type="text/javascript">
function fn() {
     .....
}
</script>

When I do this, it doesn't seem to be calling fn().

2 Answers 2

8

Your script tags are incorrectly nested.

<script type="text/javascript">
    function fn() {
         .....
    }
</script>
<script type="text/javascript" src="js/foo.js"></script>

And to actually answer your question: Yes, it is possible.

Sign up to request clarification or add additional context in comments.

1 Comment

That solved my problem, but actually the problem was that my javascript include was delcared before the function. Changing the order solved my problem. thx.
1

Definitely possible, but not recommended. If you are calling a function that has been nested within your html, that function should probably be in the file that is calling it. Unless of course, you have your own library of helper and utility functions, and this function you are calling could reside there. This will keep a nice separation between your program logic(JavaScript), and your content(HTML). for example:

<!-- Your Helper Library that holds useful functions -->
<script type="text/javascript" src="helpers.js"></scrip>

<!-- Your Program Logic that makes use of your helper functions -->
<script type="text/javascript" src="programlogic.js"></scrip>

I hope this has helped!

-Mike

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.