- JavaScript is Case Sensitive
- JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent:
name="Hege";
name = "Hege"; |
Break up a Code Line
You can break up a code line within a text string with a backslash. The example below will be displayed properly:
document.write("Hello \
World!"); |
However, you cannot break up a code line like this:
document.write \
("Hello World!"); |
Insert Special Characters
Backslash (\) is used to insert apostrophes, new lines, quotes, etc…into a text string.
var txt="We are the so-called "Vikings" from the north.";
document.write(txt); |
- A string is started and stopped with either single or double quotes àabove string will be chopped to: We are the so-called
- We must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:
var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt); |
Another Example:
document.write ("You \& I are singing!"); |
This will produce:
Table below lists special characters that can be added to a text string with the backslash sign:
Code |
Outputs |
\' |
single quote |
\" |
double quote |
\& |
ampersand |
\\ |
backslash |
\n |
new line |
\r |
carriage return |
\t |
tab |
\b |
backspace |
\f |
form feed |
Write text on web page
<html>
<body>
<script type="text/JavaScript">
document.write("Hello World!");
</script>
</body>
</html> |
Use JavaScript to write HTML tags on web page
<html>
<body>
<script type="text/JavaScript">
document.write("<h1>This is a header</h1>");
</script>
</body>
</html> |
Where to Put the JavaScript
- JavaScripts in the body section à executed WHILE the page loads.
- JavaScripts in the head section à executed when CALLED.
JavaScripts in a page will be executed
- while the page loads into the browser.
- when a user triggers an event.
Scripts in the head section executed when:
- Called, or when
- an event is triggered,
- When you place a script in the head section, you must ensure that the script is loaded before anyone uses it.
Scripts in the body section executed when:
- Page loads go in the body section.
- When you place a script in the body section it generates the content of the page.
Using an External JavaScript
- To run same JavaScript on several pages, write a JavaScript in an external file.
- Save the external JavaScript file with a .js file extension.
- External script cannot contain the <script> tag!
- To use the external script, point to the .js file in the "src" attribute of the <script> tag:
- Place the script exactly where you normally would write the script!
|