This document provides an introduction to basic JavaScript concepts like inserting JavaScript into HTML documents using the <script> tag, declaring JavaScript variables, and where to place scripts within HTML documents. It discusses using <script> tags in the <head> and <body> sections, as well as linking to external JavaScript files. The document also covers JavaScript variable naming rules and how to assign values to variables.
2. Learning Outcome
At the end of this lesson, students should be
able to:
i) Insert JavaScripts in HTML documents
ii) Declare JavaScript variables in HTML
documents
3. JavaScript Syntax
• The HTML <script> tag is used to insert a JavaScript into an
HTML page.
The <script> tags tell
the browser to expect
a script in between
them.
<html>
<body>
<script type="text/javascript">
document.write("JavaScript is not Java");
</script>
</body>
This part that
</html>
writes/display the
actual text
3
4. Where to put your scripts?
1.
2.
3.
4.
Scripts in <head>
Scripts in <body>
In both the body and the head section
Using an External JavaScript
4
5. Where to put your scripts? <head>.
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
5
6. Where to put your scripts? <body>.
<html>
<body>
<script type="text/javascript">
document.write("JavaScript is not Java");
</script>
</body>
</html>
6
7. Where to put your scripts? <head> and <body>
• <html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
7
8. Where to put your scripts? External javascript
• <html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
JavaScript external
</body>
file with a .js file
</html>
extension.
8
9. 9
JAVASCRIPT VARIABLES
Rules for variable names:
• Variable names are case sensitive
• They must begin with a letter or the underscore character
• You can create a variable with the var statement:
var strname = some value
• You can also create a variable without the var statement:
strname = some value
•
Assign a Value to a Variable
var strname = "Hege"
Or like this:
strname = "Hege"