Question

EDIT:[Honestly this works fine you can read my edit comment below.]

So I am very new to JavaScript. This book I have tells me that I can write the script code in another file that has a .js extension. What it doesn't tell me is what should be in that .js extension.

<html>
<head>
<title>Title of Document</title>

<script src="path/to/file/fileName.js"></script>  
</head>

<body>
The content of
your page goes here. 
</body>
</html>

Lets say I wanted to make an alert message in the java script file. Inside the "fileName.js" would all I write be:

alert("This is an alert box");

and then save it and call it quits? Cause that is what I have so far and nothing doing.

EDIT:

Ok I want to add this in for anyone in trouble like I was. Turns out, this works perfectly. The comments below are a great help for further information. But the thing I did not realize was that on my Mac I needed to start the path to file at /Users. I feel dumb but at least I figured it out. Thanks all for your help.

Was it helpful?

Solution 2

Generally your js files will have objects and Methods that are called/used from you main page. So you html wiil look like :

<html>
    <head>
        <title>Title of Document</title>

        <script src="path/to/file/fileName.js"></script>  
    </head>

    <body onload="showAlert();">
        The content of
        your page goes here. 
    </body>
</html>

and you js will look like:

function showAlert(){
    alert("This is an alert box");
}

OTHER TIPS

Use " instead of :

<script src="path/to/file/fileName.js"></script>
            ^                        ^

Look into events and listeners. For example, if you want the alert to come up when the page loads, your html file would have:

<body onload="functionName()">

</body>

And you javascript file would have:

function functionName() {
    alert("alert message");
}

Usually you would write your Javascript code as a series of functions that you can call whenever you need. So yes, you can write a single statement the way you did but most times its functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top