Chapter 4 Java Script
Chapter 4 Java Script
Chapter 4 Java Script
What is JavaScript?
A script is a small piece of program that can add interactivity to your website. For
example, a script could generate a pop-up alert box message, or provide a dropdown
menu. This script could be written using JavaScript
.
JavaScript (js) is a light-weight object-oriented programming language which is used by
several websites for scripting the webpages.
JavaScript can change HTML Content.
One of many JavaScript HTML methods is getElementById().
The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
JavaScript accepts both double and single quotes:
Example
document.getElementById('demo').innerHTML = 'Hello JavaScript';
JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element is a variant of changing an HTML attribute:
Example
document.getElementById("demo").style.fontSize = "35px";
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
Example
document.getElementById("demo").style.display = "none";
JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
Example
document.getElementById("demo").style.display = "block";
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
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 keywords are reserved words. Reserved words cannot be used as names for
variables.
JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
JavaScript comments can also be used to prevent execution, when testing alternative
code.
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a single line comment at the end of each line to explain the code:
Example
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This 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.";
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:
Example
<!DOCTYPE html>
<html>
<body>
<h1>MyFirstWebPage</h1>
<p>MyFirstParagraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Changing the innerHTML property of an HTML element is a common way to display data in
HTML.
Using document.write()
Example
<!DOCTYPE html>
<html>
<body>
<h1>MyFirstWebPage</h1>
<p>Myfirstparagraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is loaded, will delete all existing HTML:
Example
<!DOCTYPE html>
<html>
<body>
<h1>MyFirstWebPage</h1>
<p>Myfirstparagraph.</p>
<button type="button" onclick="document.write(5+6)">Tryit</button>
</body>
</html>
Using window.alert()
</body>
</html>
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display
data.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript Print
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print
the content of the current window.
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="window.print()">Printthispage</button>
</body>
</html>
JavaScript Statements
Example
let x,y,z; / Statement 1
x= 5; // Statement 2
y= 6; // Statement 3
z = x + y; // Statement 4
JavaScript Variables
Using var
Using let
Using const
Variables
Variables are containers for storing data (values).
In this example, x, y, and z, are variables, declared with the var keyword:
Example
var x= 5;
var y= 6;
var z = x + y;
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
a = 5; b = 6; c = a + b;
JavaScript Dollar Sign $
Remember that JavaScript identifiers (names) must begin with:
A letter (A-Z or a-z)
A dollar sign ($)
Or an underscore (_)
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:
Example
var $$$= "HelloWorld";
var $= 2;
var $myMoney= 5;
Using the dollar sign is not very common in JavaScript, but professional programmers
often use it as an alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $ is used to select HTML
elements. In jQuery $("p"); means "select all p elements".
Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:
Example
var _lastName= "Johnson";
var _x= 2;
var _100= 5;
Using the underscore is not very common in JavaScript, but a convention among
professional programmers is to use it as an alias for "private (hidden)" variables.
Assignment
let x = 10;
Adding
let x = 5;
let y = 2;
let z = x + y;
Multiplying
let x = 5;
let y = 2;
let z = x * y;
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Assignment
let x = 10;
x += 5;
Example
let text1= "John";
let text2= "Doe";
let text3 = text1 + " " + text2;
John Doe
The += assignment operator can also be used to add (concatenate) strings:
Example
let text1= "What a very ";
text1 += "nice day";
Adding two numbers will return the sum, but adding a number and a string will return a string:
Example
let x= 5 + 5;
let y= "5" + 5;
let z= "Hello" + 5;
10
55
Hello5
Operator Description
== equal to
!= not equal
? ternary operator
Operator Description
|| logical or
! logical not
Any numeric operand in the operation is converted into a 32 bit number. The result is converted
back to a JavaScript number.
The JavaScript if-else statement is used to execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
if(expression){
//content to be evaluated
}
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Let’s see the example of if -else statement in JavaScript to find out the even or odd
number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
4.9JavaScript Functions
A function allows you to define a block of code, give it a name and the execute it as many times
as you want.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Event Handlers Example</title>
<body>
<p onmouseover = "EventHandler();">Bring your mouse here to see an alert</p>
</body>
</html>
4.10. JavaScript DOM (Document object Model)
The HTML DOM defines a standard way for accessing and manipulating HTML
documents. It presents an HTML document as a tree-structure.
Example
<h1 id="demo">This is a Heading</h1>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
When you want to access HTML elements with JavaScript, you have to find the elements first.
The easiest way to find an HTML element in the DOM, is by using the element id.
This example finds the element with id="intro":
Example
var myElement = document.getElementById("intro");
If the element is found, the method will return the element as an object (in myElement).
If the element is not found, myElement will contain null.
Finding HTML Elements by Tag Name
This example finds all <p> elements:
Example
var x = document.getElementsByTagName("p");
This example finds the element with id="main", and then finds all <p> elements
inside "main":
Example
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
Finding HTML Elements by Class Name
If you want to find all HTML elements with the same class name, use
getElementsByClassName().
This example returns a list of all elements with class="intro".
Example
var x = document.getElementsByClassName("intro");
Finding elements by class name does not work in Internet Explorer 8 and
earlier versions.
Finding HTML Elements by CSS Selectors
If you want to find all HTML elements that matches a specified CSS selector
(id, class names, types, attributes, values of attributes, etc), use the
querySelectorAll() method.
This example returns a list of all <p> elements with class="intro".
Example
var x = document.querySelectorAll("p.intro");
The querySelectorAll() method does not work in Internet Explorer 8 and earlier
versions.
Note: The document object represents an html document. It forms DOM (Document
Object Model).
4.11. Form Processing using JavaScript
In order to program BOM objects, they must be identified to the scripts that
manipulate their properties and methods.
Reference Object
window The main browser window
window.navigator Information about the browser itself
window.screen The user's screen
window.history URLs visited by a user
window.location The current URL
The document appearing in the main browser
window.document (document)
window
An HTML element appearing in a document and
identified by its assigned id value.
document.getElementById("id")
window.document.getElementById("header");
Result is:
Page hostname is
Result is:
Page protocol is file:
The window.location.port property returns the number of the internet host port (of
the current page).
Example
Display the name of the host:
document.getElementById("demo").innerHTML =
"Port number is " + window.location.port;
Result is:
Port number is
Most browsers will not display default port numbers (80 for http and 443 for https)
Cookies were invented to solve the problem "how to remember information about the
user":
When a user visits a web page, his/her name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his/her name.