JavaScript Lectuers Alhemah
JavaScript Lectuers Alhemah
1 What is JavaScript
2 Where Does Javascript
GO?
3 JavaScript Syntax
2
Section 1 of 3
WHAT IS JAVASCRIPT
What we've learned so far
4
What is JavaScript
A lightweight programming language ("scripting language")
Used to make web pages interactive
5
What isn’t JavaScript
Although it contains the word Java, JavaScript and Java are vastly
different programming languages with different uses.
Java is a full-fledged compiled, object-oriented language, popular for its
ability to run on any platform with a JVM installed.
JavaScript is an interpreted language and it is one of the world’s most
popular languages, with fewer of the object-oriented features of Java,
and runs directly inside the browser, without the need for the JVM.
6
Why Study JavaScript?
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages.
2. CSS to specify the layout of web pages.
3. JavaScript to program the behaviour of web pages.
Web pages are not the only place where JavaScript is used. Many
desktop and server programs use JavaScript. Node.js is the best
known. Some databases, like MongoDB and CouchDB, also use
JavaScript as their programming language.
7
Client-Side Scripting
Let the client compute
The idea of client-side scripting refers to the client machine (i.e., the
browser) running code locally rather than relying on the server to
execute code and return the result.
8
Client-Side Scripting
There are many advantages of client-side scripting:
Processing can be offloaded from the server to client machines,
9
Client-Side Scripting
The disadvantages of client-side scripting are mostly related to how
programmers use JavaScript in their applications.
There is no guarantee that the client has JavaScript enabled.
and maintain.
10
JavaScript History
JavaScript was introduced by Netscape in their Navigator browser
back in 1996.
11
JavaScript Implementations
Though JavaScript and ECMAScript are often used synonymously,
JavaScript is much more than just what is defined in ECMA-262.
12
Section 2 of 3
Embedded
External
14
Inline JavaScript
Inline JavaScript refers to the practice of including JavaScript code
directly within certain HTML attributes.
<a href="JavaScript:OpenWindow();"> more info </a>
<input type="button" onclick="alert('Are you sure?');" />
15
Embedded JavaScript
Better
16
External JavaScript
Better
External scripts are practical when the same code is used in many
different web pages.
17
Section 3 of 3
JAVASCRIPT SYNTAX
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are
constructed.
We will briefly cover the fundamental syntax for the most common
programming constructs including:
variables,
assignment
conditionals
loops
functions
19
Variables
Variables in JavaScript are dynamically typed, meaning a variable can
be an integer, and then later a string, then later an object, if so
desired.
20
Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Ex:
var x = 5; var x = 5; var x = 5;
var y = 2; var z = x ** 2; x++;
var z = x + y; // result is 25 var z = x;
21
Assignment Operators
Assignment operators assign values to JavaScript variables.
22
String Operators
The +, += operators can be used to add (concatenate) strings.
Ex:
var txt1 = "John"; var txt1 = "What a very ";
var txt2 = "Doe"; txt1 += "nice day";
var txt3 = txt1 + " " + txt2;
The result of txt1 will be:
The result of txt3 will be: John Doe
What a very nice day
23
Comparison Operators
True or not True
24
Conditional (Ternary) Operator
JavaScript also contains a conditional operator that assigns a value to
a variable based on some condition.
Ex:
var age= 10;
25
Logical Operators
The Boolean operators AND, OR, and NOT are represented with &&
(and), || (or), and ! (not).
Operator Example
&& (x < 10 && y > 1) is true
|| (x == 5 || y == 5) is false
! !(x == y) is true
26
Conditionals
If, else if, …, else
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
// condition2 is true
} else {
// block of code to be executed if the condition1 is false and
// condition2 is false
}
27
Conditionals
If, else if, …, else
Ex:
28
Conditionals
switch
Syntax: switch(expression) {
case x:
// code block • When JavaScript reaches a break keyword, it
break; breaks out of the switch block. This will stop
case y: the execution of inside the block.
// code block
break; • The default keyword specifies the code to run
default: if there is no case match.
// code block
}
It works as follows:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
29
Conditionals
switch
30
Loops
Round and round we go
31
For Loop
Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
This statement begins with the for keyword and has the components
placed between ( ) brackets, semicolon (;) separated as shown.
32
For/in Loop
It is used to enumerate the non-symbol keyed properties of an object.
Syntax:
for (property in expression) {
statement
}
Note: the for-in statement simply doesn’t execute the body of the
loop if the variable representing the object to iterate over is null or
undefined.
33
For/of Loop
It is used to loop through elements in an iterable object.
Example:
for (var el of [2,4,6,8]) {
document.write(el); // 2 4 6 8
}
for (var el in [2,4,6,8]) {
document.write(el); // 0 1 2 3
}
Note: the for-of statement will throw an error if the entity that it is
attempting to iterate over does not support iteration.
34
While Loops
Syntax:
while (condition) {
// code block to be executed
}
While loops normally initialize a loop control variable before the loop,
use it in the condition, and modify it within the loop.
35
Do/While Loop
Syntax:
do {
// code block to be executed
}
while (condition);
The loop will always be executed at least once, even if the condition is
false, because the code block is executed before the condition is
tested.
36
Functions
A JavaScript function is a block of code designed to perform
a particular task.
Functions are the building block for modular code in JavaScript, and
are even used to build pseudo-classes.
They are defined by using the reserved word function and then the
function name and (optional) parameters.
37
Functions
Ex:
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
called as: var x = myFunction(4, 3);
Ex:
function power(x, y) {
var pow=1;
for (var i=0; i<y; i++) {
pow = pow*x;
}
return pow;
}
called as: var x =power(2, 3);
38
Javascript Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and
Prompt box.
Alert Box
It 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"); or alert("sometext");
Confirm Box
It 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"); or confirm("sometext");
39
Javascript Popup Boxes
Prompt Box
It 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","defaultText");
or prompt("sometext","defaultText");
40
Errors using try and catch
When the browser’s JavaScript engine encounters an error, it will
throw an exception.
41
Errors using try and catch
The try/catch statement handles some or all of the errors that may
occur in a block of code, while still running code.
The try statement allows you to define a block of code to be tested for
errors while it is being executed.
Ex:
try {
nonexistantfunction("hello");
}
catch(err) {
alert("An exception was caught:" + err);
}
42
Comments
There are two styles of comment in JavaScript:
The end-of-line comment, which starts with two slashes //.
The block comment, which begins with /* and ends with */.
Ex:
var x = 5; // I will be executed
43
JavaScript Output
JavaScript can "display" data in different ways:
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Using document.write():
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
44
JavaScript Output
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>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
45
JavaScript Output
Using window.alert():
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html> <!DOCTYPE html>
<html>
Using console.log(): <body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
46
Web Programming
1 JavaScript Objects
2 The DOM
2
Section 1 of 2
JAVASCRIPT OBJECTS
Javascript Objects
ECMA-262 defines an object as an unordered collection of properties.
Each property or method is identified by a name that is mapped to
a value.
Object literals became the preferred pattern for creating such objects.
var person = { name: "Nicholas",
age: 29,
job: "Software Engineer",
sayName: function() { return this.name; }
};
4
Object Properties
The name:values pairs in JavaScript objects are called properties.
Bracket notation allows you to use variables for property access, and
to use property names that contains characters that would be either
a syntax error or a keyword/reserved word.
var propertyName = "name";
person[propertyName]="Nicholas";
console.log(person[propertyName]); // "Nicholas"
person["first name"] = "Nicholas";
5
Object Properties
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
// Display some data from the object:
document.getElementById("demo").innerHTML = person.firstName + " " +
person.lastName;
</script>
</body>
</html>
6
Object Methods
Objects can also have methods.
7
Object Methods
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display some data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
8
Object Creation
Although using the Object constructor or an object literal are convenient
ways to create single objects, there is an downside: Creating multiple
objects with the same interface requires a lot of code duplication.
12
Object Creation
The Prototype Hierarchy
Whenever a property is accessed for reading on an object, a search is started to
find a property with that name. The search begins on the object instance itself.
If a property with the given name is found on the instance, then that value is returned.
If the property is not found, then the search continues up the pointer to the prototype. If
the property is found on the prototype, then that value is returned.
If you add a property to an instance that has the same name as a property on the
prototype, you create the property on the instance, which then masks the property
on the prototype.
function Person() {}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function() {
console.log(this.name);
};
var person1 = new Person();
var person2 = new Person();
person1.name = "Greg";
console.log(person1.name); // "Greg" - from instance
console.log(person2.name); // "Nicholas" - from prototype
13
Objects Included in JavaScript
In JavaScript, almost "everything" is an object.
Booleans can be objects (if defined with the new keyword)
Numbers can be objects (if defined with the new keyword)
Strings can be objects (if defined with the new keyword)
Dates are always objects
Maths are always objects
Arrays are always objects
Dom objects
14
Boolean
A JavaScript Boolean represents one of two values: true or false.
Note: You can use the JavaScript typeof operator to find the type of
a JavaScript variable.
15
Boolean Methods
You can use the Boolean() function to find out if an expression (or
a variable) is true.
Boolean(10 > 9) // returns true
16
Number
JavaScript does not define different types of numbers, like integers,
short, long, floating-point etc.
17
Number Properties and Methods
toString() method returns a number as a string. All number methods
can be used on any type of numbers (literals, variables, or expressions).
var x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23
18
Number Properties and Methods
parseInt() method parses a string and returns a whole number.
Spaces are allowed. Only the first number is returned.
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
19
Number Properties and Methods
MAX_VALUE property returns the largest possible number in
JavaScript.
20
String
JavaScript strings are used for storing and manipulating text.
21
:
String
Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
22
String Properties and Methods
The length property returns the length of a string.
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
The result: sln= 26
23
String Properties and Methods
search() method accepts a single argument, which is either a regular-
expression string or a RegExp object, and returns the index of the first
pattern occurrence in the string or –1 if it’s not found.
var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
console.log(pos);
The result: pos= 1
24
String Properties and Methods
slice(), substr(), and substring() methods return a substring of the string
they act on, and all accept either one or two arguments. The first argument
is the position where capture of the substring begins; the second argument,
if used, indicates where the operation should stop:
For slice() and substring(), the second argument is the position before which
capture is stopped.
For substr(), the second argument is the number of characters to return.
If the second argument is omitted in any case, it is assumed that the ending
position is the length of the string.
There are different behaviours for these methods when an argument is
a negative number:
For the slice() method, a negative argument is treated as the length of the string
plus the negative argument.
For the substr() method, a negative first argument is treated as the length of the
string plus the number, whereas a negative second number is converted to 0.
For the substring() method, all negative numbers are converted to 0.
25
String Properties and Methods
Ex: var stringValue = "hello world";
var res1=stringValue.slice(3);
var res2=stringValue.substring(3);
var res3= stringValue.substr(3);
var res4=stringValue.slice(3, 7);
var res5 = stringValue.substring(3, 7);
var res6= stringValue.substr(3, 7);
The result: res1= "lo world" res2= "lo world"
res3= "lo world" res4= "lo w"
res5= "lo w" res6= "lo worl"
26
String Properties and Methods
toUpperCase() method converts string to upper case. While toLowerCase()
method converts string to lower case.
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
var text3 = text1.toLowerCase(); // text3 is text1 converted to lower
The result: text2= "HELLO WORLD!"
text3= "hello world!"
27
String Properties and Methods
charAt() method returns the character at a specified index in a string.
var str = "HELLO WORLD";
var c= str.charAt(0);
The result: c="H"
28
Date Object
The Date object is used to work with dates and times.
Date objects are created with new Date().
There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Ex:
var d = new Date(); // creates a new date object with the current date and time
var d = new Date("October 13, 2014 11:13:00"); // Mon Oct 13 2014 11:13:00 GMT+0300
var d = new Date(2019, 11, 24, 10, 33, 30, 0); // Tue Dec 24 2019 10:33:30 GMT+0200
29
Date Object methods
getDate() method returns the day of the month (from 1 to 31) for the
specified date.
getDay() method returns the day of the week (from 0 to 6) for the
specified date.
getMonth() method returns the month (from 0 to 11) for the specified
date, according to local time.
getFullYear() method returns the year (four digits for dates between
1000 and 9999) of the specified date.
getHours() method returns the hour (from 0 to 23) of the specified
date and time.
30
Date Object methods
getSeconds() method returns the seconds (from 0 to 59) of the
specified date and time.
31
Date Object methods
Ex:
var d = new Date("July 21, 1983 01:15:00");
32
Math Object
The JavaScript Math object allows you to perform mathematical tasks
on numbers.
33
Math Object
Math.ceil(x) returns the value of x rounded up to its nearest integer.
Math.ceil(4.4); // returns 5
34
Math Object
Math.min() and Math.max() can be used to find the lowest or highest
value in a list of arguments.
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Math.max(0, 150, 30, 20, -8, -200); // returns 150
35
Array Object
As in other languages, Javascript arrays are ordered lists of data, but
unlike in other languages, they can hold any type of data in each slot.
36
Array Properties and Methods
length property of an array returns the length of an array (the number
of array elements).
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
forEach() method Runs the given function on every item in the array.
This method has no return value. var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fLen = fruits.length;
// looping array elements
fruits.forEach(myFunction);
text = "<ul>";
text += "</ul>";
// looping array elements
for (i = 0; i < fLen; i++) {
function myFunction(value) {
text += "<li>" + fruits[i] + "</li>";
text += "<li>" + value + "</li>";
}
}
text += "</ul>";
37
Array Properties and Methods
push() method adds a new element to an array (at the end) and
returns the array’s new length.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x=fruits.push("Lemon"); // adds a new element (Lemon) to fruits
and the value of x is 5
pop() method removes the last element of an array, and returns that
element.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var f= fruits.pop(); // removes the element (Mango) from fruits and returns it
so the value of f is Mango
shift() method removes the first item of an array, and returns that
element. unshift() method adds a new element to an array (at the
beginning) and returns the new array length.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var f= fruits.shift(); // removes the element (Banana) from fruits and returns it
so the value of f is Banana
38
Array Properties and Methods
concat() method is used to join two or more arrays.
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
The result: ["Cecilie", "Lone", "Emil", "Tobias", "Linus"]
sort() method sorts the items of an array. By default, the sort() method
sorts the values as strings in alphabetical and ascending order.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
The result: ["Apple", "Banana", "Mango", "Orange"]
39
Section 2 of 2
The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
41
DOM Example
42
DOM Nodes
In the DOM, each element within the HTML document is called a node. If
the DOM is a tree, then each node is an individual branch.
There are:
Element nodes
Text nodes
Attribute nodes
Comment nodes
All nodes in the DOM share a common set of properties and methods.
43
DOM Nodes
Element, text and attribute nodes
44
DOM Nodes
Essential Node Object properties
Property Description
attributes returns a collection of the specified node's attributes, as a NamedNodeMap
object
childNodes Returns a collection of an element's child nodes (including text and
comment nodes) as a NodeList object.
firstChild returns the first child node of the specified node, as a Node object
lastChild returns the last child node of the specified node, as a Node object
nextSibling returns the node immediately following the specified node, in the same tree
level, as a Node object
nodeName Returns the name of a node
nodeType Returns the node type of a node
nodeValue Sets or returns the value of a node
parentNode returns the parent node of the specified node, as a Node object.
previousSibling returns the previous node of the specified node, in the same tree level, as
a Node object.
45
Example1
<body>
<img id="myImg" alt="Flower" src="klematis.jpg" width="150" height="113">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myImg");
var txt = "";
var i;
for (i = 0; i < x.attributes.length; i++) {
txt = txt + x.attributes[i].name + " = " + x.attributes[i].value + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
46
Example2
<script>
function myFunction() {
var c = document.body.childNodes;
var txt = "";
var i;
for (i = 0; i < c.length; i++) {
txt = txt + c[i].nodeName + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
47
Example3
<body>
<p id="p1">Node Object Properties Example:</p><div id="d1">the list is:</div>
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
<button onclick="myFunction()">Try it</button>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<script>
function myFunction() {
var list1 = document.getElementById("myList").firstChild.innerHTML;
var list2 = document.getElementById("myList").lastChild.innerHTML;
var x = document.getElementById("p1").parentNode.nodeName;
var y = document.getElementById("p1").nextSibling.innerHTML;
document.getElementById("demo1").innerHTML = list1;
document.getElementById("demo2").innerHTML = list2;
document.getElementById("demo3").innerHTML = x;
document.getElementById("demo4").innerHTML = y;
}
</script>
</body>
48
Document Object
One root to ground them all
49
Accessing nodes
getElementById(), getElementsByTagName()
50
Example4
<head> <style> .democlass { color: red; } </style> </head>
<body>
<h1> DOM Example</h1>
<h1> Hello World</h1>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var s = document.createElement("br");
document.body.appendChild(s);
var t = document.createTextNode("this is text node");
document.body.appendChild(t);
var v = document.createElement("br");
document.body.appendChild(v);
var btn = document.createElement("button");
btn.innerHTML = "CLICK ME";
document.body.appendChild(btn);
var h1 = document.getElementsByTagName("h1")[0];
var att = document.createAttribute("class");
att.value = "democlass";
h1.setAttributeNode(att); }
</script>
</body>
51
Element node Object
The type of object returned by the method document.getElementById()
is an Element object.
The returned Element Node object has the node properties mentioned
earlier. It also has a variety of additional properties.
Property Description
className The current value for the class attribute of this HTML element.
innerHTML Represents all the things inside of the tags. This can be read or written to and is
the primary way which we update particular div's using JS.
style The style attribute of an element. We can read and modify this property.
52
More Properties
Some Specific HTML DOM Element Properties for Certain Tag Types
While the previous properties are available for all HTML elements,
there are some HTML elements that have additional properties that
can be accessed.
Property Description Tags
href The href attribute used in a tags to specify a URL to link to. a
name The name property is a bookmark to identify this tag. a, input, textarea, form
Unlike id which is available to all tags, name is limited to
certain form related tags.
src Links to an external URL that should be loaded into the img, input, script
page (as opposed to href which is a link to follow when
clicked)
value The value is related to the value attribute of input tags. Input, textarea, submit
Often the value of an input field is user defined, and we
use value to get that user input.
53
Example5
<body>
<p><a id="myAnchor" href="http://www.microsoft.com">Microsoft</a></p>
<form>Name: <input type="text" id="myText" name="fname" value="Eva"></form>
<br>
<button onclick="myFunction()">Try it</button>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
function myFunction() {
var x = document.getElementsByTagName("a")[0].id;
document.getElementById("demo1").innerHTML = x;
document.getElementById("myAnchor").href = "http://www.cnn.com/";
document.getElementById("demo2").innerHTML = "The link above now
goes to www.cnn.com.";
var y = document.getElementById("myText").name ;
document.getElementById("demo3").innerHTML = y;
}
</script>
</body>
54
Example6
<body>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
document.getElementById("p2").style.backgroundColor = "#FFFF00";
</script>
55
Web Programming
1 JavaScrip Events
2 Forms
2
Section 1 of 2
JAVASCRIPT EVENTS
JavaScript Events
HTML events are "things" that happen to HTML elements like:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
JavaScript lets you execute code when events are detected as response
to that event.
4
JavaScript Events
A brave new world
5
Event Types
There are several classes of event, with several types of event within
each class specified by the W3C:
mouse events
keyboard events
form events
frame events
6
Mouse events
Event Description
7
Keyboard events
Event Description
8
Form Events
Event Description
onblur A form element has lost focus (that is, control has moved to a different
element, perhaps due to a click or Tab key press).
onchange Some <input>, <textarea> or <select> field had their value change.
This could mean the user typed something, or selected a new choice.
onfocus Complementing the onblur event, this is triggered when an element
gets focus (the user clicks in the field or tabs to it)
onreset HTML forms have the ability to be reset. This event is triggered when
that happens.
onselect When the users selects some text. This is often used to try and prevent
copy/paste.
onsubmit When the form is submitted this event is triggered. We can do some
pre-validation when the user submits the form in JavaScript before
sending the data on to the server.
9
Frame Events
Frame events are the events related to the browser frame that
contains your web page.
Event Description
10
Handling Events
HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
<element event='some JavaScript'> or
<element event="some JavaScript">
Ex:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date.</p>
<button onclick="document.getElementById('demo').innerHTML=Date()">
The time is?</button>
<p id="demo"></p>
</body>
</html>
11
Handling Events
JavaScript code is often several lines long. It is more common to see
event attributes calling functions.
Ex:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
12
Example1
<!DOCTYPE html>
<html>
<body>
<p>Click "Try it" to execute the displayDate() function.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick = displayDate;
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
13
Example2
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
14
Example3
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h2>Hello World!</h2>
</body>
</html>
15
Example4
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name:
<input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which
transforms the input text to upper case.</p>
</body>
</html>
16
Example5
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
</body>
</html>
17
Example6
<!DOCTYPE html>
<html>
<body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>
<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>
18
Example7
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which
changes the background-color.</p>
</body>
</html>
19
Section 2 of 2
FORMS
HTML DOM forms Collection
The forms collection returns a collection of all <form> elements in the
document as HTMLCollection object which is an array-like list of HTML
elements..
The elements in the collection are sorted as they appear in the source
code.
Syntax: document.forms
Properties
Property Description
Returns the number of <form> elements in
length
the collection.
21
HTML DOM forms Collection
Methods
Property Description
Returns the <form> element from the collection with
the specified index (starts at 0).
[index]
Note: Returns null if the index number is out of range
Returns the <form> element from the collection with
the specified index (starts at 0).
item(index)
Note: Returns null if the index number is out of range
Returns the <form> element from the collection with
the specified id.
namedItem(id)
Note: Returns null if the id does not exist
22
Example
<!DOCTYPE html>
<html>
<body>
<form>
First Name: <input type="text" name="fname" value="Eva"><br>
Last Name: <input type="text" name="lname" value="Hriekes">
</form>
<p>Click the button to display the number of form elements in the document.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.forms.length;
document.getElementById("demo").innerHTML= " The number of Forms: " + x;
}
</script>
</body>
</html>
23
Form elements Collection
The elements collection returns a collection of all elements in a form as
HTMLFormsControlCollection Object.
The elements in the collection are sorted as they appear in the source
code.
Syntax: formObject.elements
Properties:
Property Description
Returns the number of elements in the
length
<form> element.
24
Form elements Collection
Methods:
Property Description
Returns the element in <form> with the specified
index (starts at 0).
[index]
Note: Returns null if the index number is out of range
Returns the element in <form> with the specified
index (starts at 0).
item(index)
Note: Returns null if the index number is out of range
Returns the element in <form> with the specified id.
namedItem(id)
Note: Returns null if the id does not exist
25
Example1
<!DOCTYPE html>
<html>
<body>
<form id = "myForm" >
First Name: <input type="text" name="fname" value= "Eva"><br>
Last Name: <input type="text" name="lname" value= "Hriekes">
<input type="submit" value="Submit">
</form>
<p>Click the "Try it" button to display the number of elements in the form.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myForm").elements.length;
document.getElementById("demo").innerHTML = "Found " + x +
" elements in the form."; }
</script>
</body>
</html>
26
Example2
<!DOCTYPE html>
<html>
<body>
<form id="myForm" action="/action_page.php">
First Name: <input type="text" name="fname" value="Eva"><br>
Last Name: <input type="text" name="lname" value="Hriekes">
<input type="submit" value="Submit">
</form>
<p>Click the "Try it" button to display the value of each element in the form.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myForm");
var txt = ""; var i;
for (i = 0; i < x.length; i++) {
txt = txt + x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = txt; }
</script>
</body>
</html>
27
Validating Forms
Form validation can be defined by many different methods:
Server side validation is performed by a web server, after input has been
sent to the server.
Client side validation is performed by a web browser, before input is sent
to a web server.
Writing code to prevalidate forms on the client side will reduce the
number of incorrect submissions, thereby reducing server load.
29
Example2
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 1 and 10:</p>
<input type ="text" id="numb">
<button type="button" onclick="myFunction()">Validate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of the 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) {
text = "Input not valid";
} else { text = "Input OK"; }
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
30
Example3- HTML file
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Form validation</title>
<link rel="stylesheet" href="style.css">
<script src="validator.js"></script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()"
action="confirmation.php" method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>
31
Example3- HTML file
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="error" id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</div>
<div class="error" id="genderErr"></div>
</div>
32
Example3- HTML file
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>
<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>
33
Example3- CSS file(style.css)
body {
font-size: 16px;
background: #f9f9f9;
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
form {
width: 300px;
background: #fff;
padding: 15px 40px 40px;
border: 1px solid #ccc;
margin: 50px auto 0;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px
}
34
Example3- CSS file(style.css)
label i {
color: #999;
font-size: 80%;
}
input, select {
border: 1px solid #ccc;
padding: 10px;
display: block;
width: 100%;
box-sizing: border-box;
border-radius: 2px;
}
.row {
padding-bottom: 10px;
}
.form-inline {
border: 1px solid #ccc;
padding: 8px 10px 4px;
border-radius: 2px;
}
35
Example3- CSS file(style.css)
.form-inline label, .form-inline input {
display: inline-block;
width: auto;
padding-right: 15px;
}
.error {
color: red;
font-size: 90%;
}
input[type="submit"] {
font-size: 110%;
font-weight: 100;
background: #006dcc;
border-color: #016BC1;
box-shadow: 0 3px 0 #0165b6;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #0165b6;
}
36
Example3-web page in the browser
37
Example3- javascript file(validator.js)
// Defining a function to display error message
function printError(elemId, hintMsg) {
document.getElementById(elemId).innerHTML = hintMsg;
}
38
Example3- javascript file(validator.js)
// Defining error variables with a default value
var nameErr = emailErr = mobileErr = countryErr = genderErr = true;
// Validate name
if(name == "") {
printError("nameErr", "Please enter your name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printError("nameErr", "Please enter a valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}
// Validate email address
if(email == "") {
printError("emailErr", "Please enter your email address");
} else {
// Regular expression for basic email validation
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printError("emailErr", "Please enter a valid email address");
39
Example3- javascript file(validator.js)
} else {
printError("emailErr", "");
emailErr = false;
}
}
// Validate mobile number
if(mobile == "") {
printError("mobileErr", "Please enter your mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if(regex.test(mobile) === false) {
printError("mobileErr", "Please enter a valid 10 digit mobile number");
} else{
printError("mobileErr", "");
mobileErr = false;
}
}
// Validate country
if(country == "Select") {
printError("countryErr", "Please select your country");
} else {
printError("countryErr", "");
countryErr = false;
}
40
Example3- javascript file(validator.js)
// Validate gender
if(gender == "") {
printError("genderErr", "Please select your gender");
} else {
printError("genderErr", "");
genderErr = false;
}
// Prevent the form from being submitted if there are any errors
if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
return false;
} else {
// Creating a string from input data for preview
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if(hobbies.length) {
dataPreview += "Hobbies: " + hobbies.join(", ");
}
// Display input data in a dialog box before submitting the form
alert(dataPreview);
} }
41
Example3-web page in the browser
42
Example3-web page in the browser
43