JavaScript Notes
JavaScript Notes
JavaScript Notes
JavaScript Introduction
JavaScript is the most popular programming language in the world.
This page contains some examples of what JavaScript can do.
This example "finds" the HTML element with id="demo", and changes its
content (innerHTML):
document.getElementById("demo").style.fontSize = "25px";
Submit
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
</body>
</html>
JavaScript and Java are completely different languages, both in concept and
design.
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
For example, a function can be executed when an event occurs, like when
the user clicks a button.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an
HTML page.
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an
HTML page.
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
External JavaScript
Scripts can also be placed in external files.
External scripts are practical when the same code is used in many different
web pages.
To use an external script, put the name of the script file in the src (source)
attribute of the <script> tag:
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
JavaScript Output
avaScript does not have any built-in print or display functions.
Using window.alert()
You can use an alert box to display data:.
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
</body>
</html>
Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines
the HTML content:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
JavaScript Syntax
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by the
computer.
In a programming language, these program instructions are
called statements.
JavaScript Variables
In a programming language, variables are used to store data values.
x = 6;
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
JavaScript Comments
Not all JavaScript statements are "executed".
One place you will find statements grouped together in blocks, are in
JavaScript functions:
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
}
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript
action to be performed.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
JavaScript can handle many types of data, but for now, just think of numbers
and strings.
Strings are written inside double or single quotes. Numbers are written
without quotes.
If you put quotes around a number, it will be treated as a text string.
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
You can also assign a value to the variable when you declare it:
var carName = "Volvo";
In the example below, we create a variable called carName and assign the
value "Volvo" to it.
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Does it make any sense to add "Volvo" to sixteen? Will produce an error or a
result?
JavaScript Arrays
JavaScript arrays are written with square brackets.
The following code declares (creates) an array called cars, containing three
items (car names):
var cars = ["Saab", "Volvo", "BMW"];
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular
task.
A JavaScript function is executed when "something" invokes it (calls it).
function myFunction(p1, p2) {
return p1 * p2; // the function returns the product of
p1 and p2
}
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
Function arguments are the real values received by the function when it is
invoked.
Function Invocation
The code inside the function will execute when "something" invokes (calls)
the function:
You will learn a lot more about function invocation later in this tutorial.
Function Return
When JavaScript reaches a return statement, the function will stop
executing.
If the function was invoked from a statement, JavaScript will "return" to
execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back
to the "caller":
Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3); // Function is called, return value
will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a
and b
}
Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce
different results.
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(32);
JavaScript Events
In the example above, the JavaScript code changes the content of the
element with id="demo".
In the next example, the code changes the content of it's own element
(using this.innerHTML):
<button onclick="this.innerHTML=Date()">The time is?</button>
Event Description
onmouseout The user moves the mouse away from an HTML element
Many different methods can be used to let JavaScript work with events:
JavaScript Forms
JavaScript Form Validation
HTML form validation can be done by a JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns
false, to prevent the form from being submitted:
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
If a form field (fname) is empty, the required attribute prevents this form
from being submitted:
<form action="demo_form.asp" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
Server side validation is performed by a web server, after input has been
sent to the server.