JavaScript Introduction
References
What Javascript Is Used For
Javascript:
- Is a programming language
- Is built into your Web browser
Javascript:
- Can add interactivity to your Web pages
- Can change a Web page after it has loaded
- Can add animation to the page
- Can add drop-down or animated menus to the page
- Can verify and process data that a user enters into a form
- Can perform mathematical calculations
- Can provide feedback to the user
- Can control the Web browser window itself
- Etc.
Here are some samples of what Javascript can allow you to do with your
Web pages. You will build some of these pages as you do the assignments
over the next few weeks:
Some alternatives to Javascript are:
- CGI Scripting
- Stands for Common Gateway Interface
- Allows Web pages to send information to programs running on a Web server
- Allows Web pages to receive information back from these programs
- May limit the speed of interactivity between your page and the programs
- Can get bogged down if many people are using the program at the same time
- Can only be written/changed by people who have access to the Web server
- Java (but not really an alternative to JavaScript)
- Not the same as Javascript
- Is a general programming language
- Is compiled and object-oriented
But JavaScript has some limitations. JavaScript:
- Can't talk directly to servers. This is one of Javascript's strengths: it runs in the browser. But
it *is* possible to indirectly get information from a server with JavaScript by using a
technology called AJAX.
AJAX is one of the topics that I cover in the PHP or ColdFusion course that I teach here in the spring.
- Can't talk directly to databases (but see the note above).
- Can't read or write files on the user's computer (other than cookies).
HTML5 update: Local Storage and Session Storage do allow
JavaScript to store data on the user's
computer in a more flexible and useful manner than with cookies.
- Can't send e-mail.
- Can't create its own graphics.
HTML5 update: The new Canvas object allows JavaScript to create simple graphics in the
user's browser.
- Works slightly differently in different browsers.
About the JavaScript Language
JavaScript is a scripting language, which means that the JavaScript
code is run by an interpreter that is built into the Web browser. An
interpreter:
- translates code into a format that the computer can
run each time the code runs, or the page is loaded
- does the translation one line of code at a time
The JavaScript that you will be learning in this course is
client-side code. Client-side means that the code runs
in the Web browser, on the user's computer.
A server-side version of JavaScript is available, but it is
proprietary and vendor-specific, and is slightly different from the
client-side code that you will learn. Server-side means that
the code runs on the Web server and can access files and databases, and
perform other server-side tasks.
JavaScript, just like any other programming language, has its own syntax.
"Syntax" means that you must type in your JavaScript instructions just
right, according to the rules that the browser's JavaScript processor understands.
We will see many more
of JavaScript's syntax rules as we go through this semester, but for now here
are some of the most important syntax rules:
- JavaScript is case-sensitive, which means that you must type the names of
the objects and data in the same upper- and lower-case form all through the page.
- Each JavaScript statement, which is a fancy name for an instruction, must end in a
semi-colon. (;)
- Strings, which are lines of text with quotes around them, cannot contain the <Enter> key. Each
string must be on one line in your text editor.
- JavaScript has many built-in methods (which are also called functions in some contexts) that you
can use to accomplish many different tasks in your code. A method/function is a pre-packaged set of
code that you use by putting its name into your code, along with optional information that gets sent into
the method/function. Some examples of built-in methods that we will look at today are:
- console.log()
- alert()
- document.write()
About Logic and Debugging
All programming languages, including JavaScript, have their own
syntax, which specifies the rules of the language. You
must follow the syntax of the language as you write the code,
or the JavaScript interpreter will not understand what you want it to do.
You must also understand and use programming logic, which means
that you must give the proper instructions to run the intended code in
the order (sequence) and under the right conditions to
accomplish
the task that you want the program to do.
Any error in syntax or logic is called a bug.
Debugging is the process (and art) of figuring out why the errors
are occurring.
One of the handiest ways to debug what is happening in your JavaScript code is a combination
of a feature in your browser and a built-in JavaScript method that you can call.
The browser feature that helps in your debugging is called the Developer's Toolkit (or some similar name, depending on
which browser you are using). You open the Developer's Toolkit in most browsers by pressing the F12 key at the top of your
keyboard.
The built-in method that is very handy for debugging is console.log(). The sample code in the section
"Creating an HTML Document with JavaScript In It" in this e-Handout has an example of console.log() in it.
Open this sample page by clicking on this link.
Press F12. Make sure the "Console" tab in the Developer's Toolkit is selected. Look in the console section for some text that says
"We made it to the end of the page!". (You will need to click the OK button in the popup window before this text shows up in the console.)
About Placing JavaScript in the <head> or <body> Sections
of HTML Documents
A Web browser renders (displays) the HTML tags and content in the order
in which it appears in the HTML document file. Any JavaScript code that
is in the document also runs in the order in which it is encountered.
You can place your JavaScript code anywhere in your HTML document.
Most people put their JavaScript code in the <head> section
of the document. But there are times when you must put the JavaScript
code in the <body> section, especially if you are using JavaScript
to change the text in the document.
The choice (except when you are changing the text and must put the JavaScript
code in the <body>) is pretty much yours. But other JavaScript
programmers will look for your code in the <head> section, so that's
normally the best place to put it.
About the <script> Tag
JavaScript programs run within an HTML document. You need to use
a <script>...</script> tag pair to enclose your JavaScript
code in the HTML document (unless the code is an event-handler
attribute inside an HTML tag -- more on that later in the course).
The <script> tag tells the browser that
a scripting engine will be needed to interpret the following code. You tell
the browser to specifically use a JavaScript scripting engine with
the type attribute of the <script> tag, unless your page is an
HTML5 page. HTML5 <script> tags do NOT require
the type attribute.
Your JavaScript <script> tag will look something like this in an HTML5 page:
<script>
/* JavaScript statements go here. */
</script>
And your JavaScript <script> tag will look something like this in an XHTML or HTML 4 page:
<script type="text/javascript">
/* JavaScript statements go here. */
</script>
Most Web browsers will default to the JavaScript scripting engine when you
omit the type attribute.
The <noscript> Tag
It is possible that the user of your page is using a browser that does not
support the <script> tag.
It is also possible for the user to turn off Javascript
processing in their browser even if the browser supports scripting.
You have a choice regarding what to do about either of these situations:
- Ignore it and frustrate the user; or
- Ask the user to upgrade their browser or to turn on Javascript processing.
In the hopes that you will choose the more reasonable and helpful of these two
options, here is some code that you can put in your page to ask the user to
turn on their browser's Javascript processing:
Simply put, you will use the <NOSCRIPT> element in your page.
The noscript element's content
is rendered (displayed) by the browser wherever it falls in the source code, but only if the
user has turned off Javascript processing or if the browser does not support scripting.
Now, here is a code sample:
<!DOCTYPE html>
<html>
<head>
<title>Noscript Sample</title>
<meta charset="UTF-8" />
<style type="text/css">
body { font-family:Arial, Helvetica, sans-serif; }
.warning { color:red; }
</style>
</head>
<body>
<script>
/* <![CDATA[ */
var today = new Date();
var theTime = today.toString();
document.write("The date and time is " + theTime + ".<br>");
/* ]]> */
</script>
<noscript>
<div class="warning">
<p>
This document requires that you have JavaScript running in your browser.
</p>
<p>
If your browser supports JavaScript, you need to
turn on scripting. Or you need to upgrade your browser
to a version that includes
JavaScript.
</p>
<p>
Please follow these instructions to turn on scripting in your browser:
</p>
<p>
<u>Microsoft Internet Explorer</u>
</p>
<ol>
<li>In the main menu, click "Tools".</li>
<li>Click "Internet Options...".</li>
<li>On the Security tab, click "Custom Level...".</li>
<li>In the Scripting section, click to enable "Active scripting".</li>
<li>Click "OK".</li>
<li>You will probably have to refresh the page.</li>
</ol>
<p>
<u>Firefox</u>
</p>
<ol>
<li>In the main menu, click "Tools".</li>
<li>Click "Options...".</li>
<li>In the Content tab, check the checkbox next to "Enable JavaScript".</li>
<li>Click "OK"</li>
<li>Click on the "Reload current page" button in the toolbar.</li>
</ol>
<p>
<u>Google Chrome</u>
</p>
<ol>
<li>Click the three vertical dots icon at the upper right of the screen.</li>
<li>Click "Settings".</li>
<li>In the "Privacy" section, click the "Site Settings" arrow.</li>
<li>In the "Content" section, click the "JavaScript" arrow.</li>
<li>Toggle/click "Allowed (recommended)" to OFF (it will say "Blocked").</li>
<li>Reload the page.</li>
</ol>
</div>
</noscript>
</body>
</html>
You can see what the above code looks like
in a browser.
How To Create an HTML Document with JavaScript Code In It
Use a text editor or an HTML editor. You can use
Notepad, HomeSite, or DreamWeaver, for instance.
Type in the following code. Actually, it would be best to copy the
HTML document template from the top of the "Resources" page in this
class site, and add to it the JavaScript parts.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Syntax</title>
<script>
/* <![CDATA[ */
// say hello world!
alert("Hello world from the <head> section!");
// Javascript can go here, but no raw HTML!
/* ]]> */
</script>
</head>
<body>
<h1>This is a JavaScript Sample.</h1>
<script>
/* <![CDATA[ */
// Put an <h3></h3> tag into the page:
document.write("<h3>Basic JavaScript Syntax</h3>");
// Here is a great debugging method:
console.log("We made it to the end of the page!");
// Javascript can go here, but no raw HTML!
/* ]]> */
</script>
</body>
</html>
Save the document as file myFirstJavascript.html.
Open the file myFirstJavascript.html in your browser.
It should look like this.
Please note these points about the above code:
-
You can use JavaScript code in any part of an HTML page.
Most JavaScript code is in the <head> section, but this is
by convention and is not a technical requirement. The
alert() statement in the above
code is in the <head>
section.
-
If, however, you are using JavaScript code to put some content
into the page with HTML tags, then the JavaScript code needs to
be in the body section of the page. The
document.write() statement in the above code
which puts the <h3> tag into
the page, is in the body section.
-
The line of code
<script>
is an HTML tag but it begins a JavaScript code section. Note
that there is a canceling </script> tag.
-
You can put comments into JavaScript code in
two ways:
-
Put two forward-slashes (//) in
front of the comment. The rest of the line after
the // will be a comment.
-
Put /* and */ at the
beginning and end of the comment. This
kind of comment can go down across multiple lines of text.
-
The lines of code that look like this:
/* <![CDATA[ */
are standard JavaScript comments, which contain a special
formatting instruction to the W3C HTML Validator.
Please NOTE that this special comment/instruction (and its ending
counterpart, described in the next list item) must be in EACH script
section of the page.
The
Validator can find this instruction even though it is in a comment.
The intstruction says to the HTML Validator, "The following part of
this page is plain character data and should not be
validated." This instruction tells the Validator not to
validate the JavaScript code.
-
The comments that look like this:
/* ]]> */
are the endings of the special W3C HTML Validator
instructions.
Please NOTE that this special comment/instruction (and its starting
counterpart, described in the previous list item) must be in EACH script
section of the page.
These ending comments/instructions end EACH part of the page which the
Validator will skip during its validation efforts.
-
The code
alert("Hello world from the <head> section!");
is using a built-in JavaScript function/method called alert(
). alert() displays the quoted sentence (inside the parentheses)
in a small popup window.
-
The code
document.write("<h3>Basic JavaScript Syntax</h3>");
is using a built-in JavaScript function/method called
document.write(). document.write()
puts the quoted text (inside the parentheses)
(and which can be HTML tags and text) into the HTML
page at that location.
-
The code
console.log("We made it to the end of the page!");
is using a very handy debugging function called
console.log() to put information into the
"developer's toolkit" console in the browser. Most
browsers open this "toolkit" when you press the F12 key.
How to Create a JavaScript Source/Include File
JavaScript is often coded directly into your HTML document. But you
can also save JavaScript code in its own separate file and include
it in your HTML document. If you choose to use JavaScript source files
in this way, you should note these points:
Open your text or HTML editor and type in this code:
<html>
<head>
<title>Multiple JavaScript Calls</title>
</head>
<body>
<script src="javascriptsource.js"></script>
<script>
document.write("This line was created with embedded JavaScript code.");
</script>
</body>
</html>
Save the document as file multipleJavascriptCalls.html
Start a new document in your text or HTML editor, and type this code:
document.write("This line was printed from the JavaScript source file.<br />");
Save the document as file javascriptsource.js
Now open file multipleJavascriptCalls.html in your browser.
It should look like this.
How to Add Comments to a JavaScript Program
Part of good programming etiquette is to put comments in your
code that explain what your code is doing, or what you were thinking
when you wrote the code, or whatever will help the next person who
looks at your code (including yourself three weeks from now!) to
understand it. Comments are non-displaying and non-executable
lines of code.
JavaScript supports two kinds of comments: line comments and
block comments.
- Line comments have two slashes (//) before the
text that makes up the comment.
- The JavaScript scripting engine will ignore the slashes and
whatever follows the slashes, to the end of the line.
- The slashes can be anywhere on a line of code, meaning that
you can add a comment on the same line as executable code,
at the end of that line of code.
- Block comments can span multiple lines. They have /*
at the beginning of the block and */ at the end of the block.
- The scripting engine will ignore everything between and
including the block comment markers.
Here is a sample of JavaScript comments:
<script>
//Let's first do an alert message:
alert("Hello, there!");
/* Now let's do another alert message,
but this time let's make it longer:
*/
alert("This is a longer alert message.");
</script>
How to Hide JavaScript from Older Browsers
If the user's browser does not handle or understand JavaScript code,
it will simply display the code in the page instead of running it. You
don't want that to happen. So you can hide your JavaScript code
from browsers that don't understand JavaScript.
You hide your JavaScript code from older browsers by putting standard
HTML comments inside the <script>...</script> tags and
around the JavaScript code itself. Browsers that do understand JavaScript
will simply ignore the HTML comment markers and will run the JavaScript
code normally.
But please note this important additional information: The closing
HTML comment just before the canceling </script> tag must be preceded
by a JavaScript line comment marker, meaning that you must put
"//" before the closing HTML comment tag.
An example follows:
<html>
<head>
<title>Hiding JavaScript from older browsers</title>
</head>
<body>
<script>
<!-- This line starts a standard HTML comment
alert("Hey! This code is working!");
// JavaScript comment ending in closing HTML comment marker -->
</script>
</body>
</html>