Where Is JavaScript Code Written?

Contact Us or call 1-877-932-8228
Where Is JavaScript Code Written?

Where Is JavaScript Code Written?

JavaScript code can be written inline (e.g, within HTML tags called event handlers), in script blocks, and in external JavaScript files. The page below shows examples of all three.

Code Sample:

<meta charset="UTF-8">
<title>JavaScript Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	window.alert("The page is loading");
	<span onclick="document.bgColor='red';">Red</span> |
	<span onclick="document.bgColor='white';">White</span>
<script type="text/javascript" src="script-1.js"></script>

As this page loads, an alert will pop up that says "The page is loading" as shown below: JavaScript Loading

After the user clicks the OK button, the page will finish loading and will appear as follows:

Code Sample:

document.write("<p>Hello, there!</p>");

The text "Hello, there!" is written dynamically by the code in JavaScriptBasics/Demos/script-1.js. We will look at the code in this file and in JavaScriptBasics/Demos/javascript-1.html again shortly.

In HTML 4, the <script> tag must contain a type attribute set to text/javascript like this: <script type="text/javascript">.

In HTML5, the assumed (default) value for type is text/javascript so it's not necessary to include the attribute, but it doesn't hurt.