Js
Js
Js
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p>JavaScript can change the content of an HTML element:</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo">This is a demonstration.</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello
JavaScript!";
}
</script>
</body>
</html>
Output:
My First JavaScript
JavaScript can change the content of an HTML element:
This is a demonstration.
The method document.getElementById() is one of many methods in the HTML
DOM.
You can use JavaScript to:
There are several chapters, about the HTML DOM, later in this tutorial.
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
</script>
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light</p>
</body>
</html>
Example
document.getElementById("demo").style.fontSize = "25px";
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<script>
function myFunction() {
var x = document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
</script>
My First JavaScript
JavaScript can change the style of an HTML element.
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 1 and 10:</p>
<input id="numb" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
//Get the value of input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
Example
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "My First JavaScript Function";
}
</script>
Often you will see scripts at the bottom of the <body> section of a web page. This can
reduce display time.
Sometimes you will see all JavaScript functions in the <head> section.
Anyway, separating HTML and JavaScript, by putting all the code in one place, is
always a good habit.
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
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
Output:
My Web Page
A Paragraph.
My Web Page
Paragraph changed.
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.
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>
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where you put the reference in the
HTML document.
External scripts cannot contain <script> tags.
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> myFunction is stored in an external file
called "myScript.js".</p>
<script src="myScript.js"></script>
</body>
</html>
Output:
My Web Page
My First External JavaScript
Note: myFunction is stored in an external file called "myScript.js".
My Web Page
A Paragraph.
Note: myFunction is stored in an external file called "myScript.js".
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 id="demo">My First Paragraph</p>
<script>
document.getElementById("demo").innerHTML = "Paragraph changed.";
</script>
</body>
</html>
The JavaScript statement above (inside the <script> tag) is executed by the web
browser:
document.getElementById("demo") is JavaScript code for finding an HTML
element using the id attribute.
In This Tutorial
Most of the time, in this tutorial, we will use the output method described above:
Writing output into a <p> element with id="demo".
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(Date());
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.write(Date());
}
</script>
</body>
</html>
Output
JavaScript Syntax
JavaScript is a programming language. The Syntax rules define how the language is
constructed.
JavaScript Syntax
JavaScript is a scripting language. It is a lightweight, but powerful, programming
language.
JavaScript Literals
In a programming language, a literal is a constant value, 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'
Expression literals evaluates (computes) to a value:
5+6
5 * 10
Array literals defines an array:
[40, 100, 1, 5, 25, 10]
JavaScript Variables
A variable can have variable values during the execution of a JavaScript. A literal is
always a constant value.
A variable is a name. A literal is value.
JavaScript Operators
JavaScript uses arithmetic operators to compute values (just like algebra):
(5 + 6) * 10
JavaScript uses an assignment operator to assign values to variables (just like algebra):
x=5
y=6
z = (x + y) * 10
The JavaScript language has many types of operators:
Type
Examples
Description
= + - * /
Described in JS Operators
== != < >
Described in JS
Comparisons
JavaScript Statements
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 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 Comments
Not all JavaScript statements are "commands". Anything after double slashes // is
ignored by the browser:
// I will not be executed
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 points = x * 10;
// Number assigned by an expression 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
We use blue color to highlight reserved words, brown for string literals, and green for
comments.
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).
function myFunction(a, b) {
return a * b;
}
Example
My First JavaScript Example
Click "Date" to display current day, date, and time.
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p>Click Date to display current day, date, and time.</p>
<button type="button" onclick="myFunction()">Date</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
Output;
My First JavaScript
Click Date to display current day, date, and time.
JavaScript Statements
In HTML, JavaScript statements are command lines executed by the web browser.
JavaScript Statements
In HTML, JavaScript statements are "commands" to the browser.
The purpose, of the statements, is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML
element identified with id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Semicolon ;
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
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDiv").innerHTML = "How are you?";
JavaScript Code Blocks
Example
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
}
In this tutorial we use 4 spaces of indentation for code blocks.
You will learn much more about functions later in this tutorial.
Example
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
Example
var x = 5;
var y = 6;
var z = x + y;
Much Like Algebra
x=5
y=6
z=x+y
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 can contain letters, digits, underscores, and dollar signs.
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Declaring (Creating) JavaScript Variables
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.
Then we "output" the value inside an HTML paragraph with id="demo":
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
It's a good programming practice to declare all variables at the beginning of a script.
In JavaScript you can always separate statements by semicolon, but then you cannot
omit the var keyword.
Wrong:
var lastName = "Doe"; age = 30; job = "carpenter";
Right;
var lastName = "Doe"; var age = 30; var job = "carpenter";
Value = undefined
In computer programs, variables are often declared without a value. The value can be
something that has to be calculated, or something that will be provided later, like user
input. Variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of the
following statement:
var carName;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like
= and +:
Example
var y = 5;
var x = y + 2;
You can also add strings, but strings will be concatenated (added end-to-end):
Example
var y = "5";
var x = y + 2;
Note that if you add a number to a string, both will be treated as strings.
You will learn a lot more about arithmetic operators later in this tutorial.
JavaScript References
At W3Schools you will find a complete reference of all JavaScript objects, Browser
objects, and HTML DOM objects.
The references contain examples for every object, every property, and every method.
Window Object
The window object represents an open window in a browser.
If a document contain frames (<frame> or <iframe> tags), the browser creates one
window object for the HTML document, and one additional window object for each
frame.
Note: There is no public standard that applies to the Window object, but all major
browsers support it.
closed
defaultStatus
document
frames
history
innerHeight
innerWidth
length
location
name
navigator
opener
outerHeight
outerWidth
Description
Returns a Boolean value indicating whether a window has been closed or not
Sets or returns the default text in the statusbar of a window
Returns the Document object for the window (See Document object)
Returns an array of all the frames (including iframes) in the current window
Returns the History object for the window (See History object)
Returns the inner height of a window's content area
Returns the inner width of a window's content area
Returns the number of frames (including iframes) in a window
Returns the Location object for the window (See Location object)
Sets or returns the name of a window
Returns the Navigator object for the window (See Navigator object)
Returns a reference to the window that created the window
Returns the outer height of a window, including toolbars/scrollbars
Returns the outer width of a window, including toolbars/scrollbars
pageXOffset
Returns the pixels the current document has been scrolled (horizontally) from
the upper left corner of the window
pageYOffset
Returns the pixels the current document has been scrolled (vertically) from the
upper left corner of the window
parent
screen
screenLeft
screenTop
screenX
screenY
self
status
top
Description
alert()
atob()
blur()
btoa()
clearInterval()
clearTimeout()
close()
confirm()
createPopup()
focus()
moveBy()
moveTo()
open()
print()
prompt()
resizeBy()
resizeTo()
scroll()
scrollBy()
scrollTo()
setInterval()
setTimeout()
stop()
Navigator Object
The navigator object contains information about the browser.
Note: There is no public standard that applies to the navigator object, but all major
browsers support it.
appCodeName
appName
appVersion
cookieEnabled
language
onLine
platform
product
userAgent
Description
Returns the code name of the browser
Returns the name of the browser
Returns the version information of the browser
Determines whether cookies are enabled in the browser
Returns the language of the browser
Determines whether the browser is online
Returns for which platform the browser is compiled
Returns the engine name of the browser
Returns the user-agent header sent by the browser to the server
javaEnabled()
Description
Specifies whether or not the browser has Java enabled
taintEnabled()