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:

JavaScriptBasics/Demos/javascript-1.html
<!DOCTYPE HTML>
<html>
<head>
<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");
</script>
</head>
<body>
<p>
	<span onclick="document.bgColor='red';">Red</span> |
	<span onclick="document.bgColor='white';">White</span>
</p>
<script type="text/javascript" src="script-1.js"></script>
</body>
</html>

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:

JavaScriptBasics/Demos/script-1.js
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.

Next