[javascript] How to call external JavaScript function in HTML

I have a small chunk of code I can't seem to get working. I am building a website and using JavaScript for the first time. I have my JavaScript code in an external file 'Marq_Msg.js' which looks like this:

var Messages = new Array();
Messages[0] = "This is message 1";
Messages[1] = "This is message 2";
Messages[2] = "This is message 3";
Messages[3] = "This is message 4";  

function scroll_messages()
{
  for (var i = 0; i < Messages.length; i++)
        document.write(Message[i]); 
}

and in my HTML file 'Index.html' I am trying to call it like this:

    <div id="logo">
        <marquee scrollamount="5" direction="left" loop="true" height="100%" width="100%">
        <strong><font color="white"><script src="Marq_Msg.js">scroll_messages()</script></font></strong>
        </marquee>
    </div>

The 'logo' div is a CSS piece that I'm trying to marquee inside of. If I put the code embedded inside the 'head' tag and call it, it works perfectly! There are a few other things id like to do with this code (like space the messages out a little) but I can't get the code to work in the first place. I've also tried adding:

<script src="Marq_Msg.js"></script>

in the 'head' tag with a separate call, that was a no go. I also tried instead using:

<script type="text/javascript" src="Marq_Msg.js">scroll_messages()</script>

Hell, i even had the function try returning a string (even hardcoded a simple "hello" to be returned) but that didnt work either with and without the 'type':

//Marq_Msg.js
function scroll_messages()
{
   return "hello";
}

//index.html
<script type="text/javascript" src="Marq_Msg.js">document.write(scroll_messages())</script>

What am I missing? Any help would be greatly appreciated!! I've looked all over Google, and every site I find wants to do it using some 'form'. I just want messages to be displayed across, no form attached.

This question is related to javascript html

The answer is


If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-

caller.html

<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">

external.js

function letMeCallYou()
{
    alert("Bazinga!!!  you called letMeCallYou")
}

Result : enter image description here