Java Script
Java Script
</html>
The method document.getElementById() is one of many methods in the HTML
DOM.
Invoke a function = Call upon a function (ask for the code in the function to be
executed).
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML
page.
The function is invoked (called) when a button is clicked:
Example:
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML
page.
The function is invoked (called) when a button is clicked:
Example:
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
External JavaScripts
Scripts can also be placed in external files.
External scripts are practical when the same code is used in many different web
pages.
External JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the source (src) attribute
of the <script> tag.
Example:
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
Javascript Output
JavaScript does not have any print or output functions.
In HTML, JavaScript can only be used to manipulate HTML elements.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
JavaScript Syntax
JavaScript is a scripting language. It is a lightweight, but powerful, programming
language.
Syntax definition: "The principles by which sentences are constructed in a
language."
The sentences of a programming language are called computer statements, or just
statements.
JavaScript Literals
In a programming language, literals are constant values like 3.14.
Number literals can be written with or without decimals, and with or without
scientific notation (e).
3.14
1001
123e5
String literals can be written with double or single quotes:
"John Doe"
'John Doe'
JavaScript Variables
In a programming language, variables are containers for storing information (data).
The equal sign (=) assigns a value to a named variable (just like in normal algebra):
x=5
length = 6
JavaScript Operators
JavaScript uses operators to compute values (just like algebra):
5+6
a*b
JavaScript can assign computed values to named variables (just like algebra):
x=5+6
y = x * 10
Expressions like 5 + 6, and x * 10, are called expression literals.
JavaScript Statements
In HTML, JavaScript statements are written as sequences of "commands" to the
HTML browser.
Statements are separated by semicolons.
x = 5 + 6;
y = x * 10;
JavaScript Keywords
A JavaScript statement often starts with a keyword. The var keyword tells the
browser to create a new variable.
var x = 5 + 6;
var y = x * 10;
JavaScript Comments
Not all JavaScript statements are "commands". Anything after double slashes // is
ignored by the browser:
// I will not be executed
JavaScript Data Types
JavaScript variables can hold many types of data: numbers, text strings, arrays,
objects and much more:
var length = 16;
// Number assigned by a number literal
var lastName = "Johnson";
// String assigned by a string literal
var cars = ["Saab", "Volvo", "BMW"];
// Array assigned by an array
literal
var person = {firstName:John, lastName:Doe};
// Object assigned by an
object literal
JavaScript Functions
JavaScript statements written inside a function, can be invoked many times
(reused).
Invoke a function = Call upon a function (ask for the code in the function to be
executed).
Example:
function myFunction(a, b)
{
return a * b;
}
JavaScript Identifiers
All programming languages must identify variables, functions, and objects, with
unique names.
These unique names are called identifiers.
Identifier names can contain letters, digits, underscores, and dollar signs, but
cannot begin with a number.
Reserved words (like JavaScript keywords) cannot be used as identifiers.
JavaScript statements
In HTML, JavaScript statements are "commands" to the browser.
Semicolon ;
Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement.
Using semicolons also makes it possible to write many statements on one line.
Writing:
a = 5;
b = 6;
c = a + b;
Is the same as writing:
a = 5; b = 6; c = a + b;
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will manipulate two different HTML elements.
Example:
Statements
Description
Break
Catch
Continue
Do..while
For
Forin
Function
If.else
Return
Switch
Throw
Try
Var
While
JavaScript Comments
JavaScript comments can be used to explain the code, and make the code more
readable.
JavaScript comments can also be used to prevent execution, when testing
alternative code.
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
The following example uses a multi-line comment (a comment block) to explain
the code:
Example:
/*
The code below will change the heading with id = "myH" and the paragraph with
id = "myp" in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
JavaScript Variables
As with algebra, JavaScript variables can be used to hold values (x = 5) or
expressions (z = x + y).
Variable can have short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Variable names must begin with a letter
Variable names can also begin with $ and _ (but we will not use it)
Variable names are case sensitive (y and Y are different variables)
Alert Box
An alert box is often used if you want to make sure information comes through
to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax:
window.alert(sometext);
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display an alert box:</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
Confirm box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax:
window.confirm(sometext);
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Prompt box
A prompt box is often used if you want the user to input a value before entering a
page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
Syntax:
window.prompt(sometext,default text);
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x;
var person = prompt("Please enter your name","Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
}
</script>
</body>
</html>
Javascript Strings
JavaScript strings are used for storing and manipulating text.
A string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
String indexes are zero-based, which means the first character is [0], the second is
[1], and so on.
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
Example:
var answer = "He is called 'John'";
String Length
The length of a string (a string object) is found in the built in property length.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = txt.length;
</script>
</body>
</html>
The lastIndexOf() method finds the last occurrence of a specified text inside a
string:
Example:
var str = "welcome";
var pos = str.lastIndexOf("e");
Replacing Content
The replace() method replaces a specified value with another value in a string:
Example:
str = "Please visit Microsoft!"
var n = str.replace("Microsoft","W3Schools");
// String