WP - Chapter Four JS
WP - Chapter Four JS
JAVASCRIPT
1
JavaScript
What is JavaScript?
JavaScript: the first Web scripting language, developed by
Netscape in 1995 which is syntactically similar to Java/C++,
but simpler & more flexible
An object-oriented scripting language that is designed
primarily for people who are building web pages using
HTML.
HTML to define the content of web pages
CSS to specify the layout of web pages
JavaScript to program the behavior of web pages
2
Cont.…
JavaScript programs are embedded within HTML documents in
source code form which is interpreted by the browser.
» Platform independence
Recall:
HTML is good for developing static pages
» can specify text/image layout, presentation, links and specifying the same
look for different pages.
In order to develop interactive/reactive pages, we must integrate
different programming language. E.g JavaScript.
In HTML, JavaScript code is inserted between <script> and
</script> tags.
The browser executes the program as it loads the page, integrating
the dynamic output of the program with the static content of
3
COMMON SCRIPTING TASKS
JavaScript can perform the following task:
» Decision making (switch and if statements)
» Used in input data validation
» Submitting forms(document.forms["myform"].submit();)
» Performing complex mathematical calculations.
» Adding dynamic features to Web pages
Image rollovers
Time-sensitive or random page elements
» utilize buttons, text boxes, clickable images, prompts, frames
» Can Change HTML Content
» Can Change the value of HTML Attributes
» Can Change HTML styles for a given element 4
Adding JavaScript code in
HTML?
Including JavaScript code inline:
Insert your JavaScript code directly inside the HTML tag using the
special tag attributes such as onclick, onmouseover, onkeypress,
onload, etc.
Example:
<body>
<button onclick="alert('Hello World!')">Click Me</button>
</body>
5
Adding JavaScript code in
HTML….
JavaScript can be placed in the <body> and the <head> sections of
an HTML page between <script> and </script> tags.
The <script> tag indicates the browser that the contained
statements are to be interpreted as executable script and not
HTML.
Java script code inside the / * Javascript code inside the
head part of our code body part of our html code */
<head> <body>
<script> <script>
function myFunction() { function myFunction() {
--- ----
}</script> }</script>
</head> </body>
6
Adding JavaScript code in
HTML….
Including an external JavaScript file in HTML (Recommended)
Scripts can also be placed in external files, when the same code is
used in many different web pages.
JavaScript files have the file extension .js.
To use an external script in html document, put the name of the
script file in the src (source) attribute of a <script> tag inside in
<head> or <body> section. <script src="script.js"></script>
//script.js <!DOCTYPE html>
function myFunction() <html><head></head>
{ <body>
document.write("Hello world"); <button type="button"
} onclick="myFunction()">Try it</button>
<script src="myScript.js"></script>
</body>
7
JavaScript Output
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
8
JavaScript Output
1. 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> output
<html>
<body>
<p>Display data using innerHTML.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script> </body></html> 9
JavaScript Output
2. Using document.write()
For testing purposes, it is convenient to use document.write()
Using document.write() after an HTML document is loaded, will
delete all existing HTML:
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<p>Display data using <p>Display data using
document.write() method.</p> document.write() method.</p>
<script> <button type="button"
document.write(5 + 6); onclick="document.write(5 + 6)">Click
</script> it</button>
</body> </body>
</html> </html>
10
JavaScript Output
2. Using window.alert()
You can use an alert box to display data.
<!DOCTYPE html>
<html>
<body>
<p>Display data using window.alert() method.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
11
JavaScript Output
3. Using window.alert()
You can use an alert box to display data.
<!DOCTYPE html>
<html>
<body>
<p>Display data using window.alert() method.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
12
JavaScript Output
4. Using console.log()
Console.log() method is used to display data in the browser console
<!DOCTYPE html>
<html>
<body>
<h2>display data using console.log() method</h2>
<script>
console.log(5 + 6);
</script>
</body>
</html>
13
JavaScript Statements
A computer program is a list of "instructions" to be "executed" by
a computer. these programming instructions are called statements.
A JavaScript program is a list of programming statements and
executed by the web browser.
JavaScript statements are composed of Values, Operators,
Expressions, Keywords, and Comments.
The statements are executed, one by one, in the same order as they
are written.
Add a semicolon at the end of each executable statement.
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c 14
JavaScript Keywords
JavaScript statements often start with a keyword to identify the
JavaScript action to be performed.
JavaScript keywords are reserved words. Reserved words cannot
be used as names for variables.
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant variable
if Marks a block of statements to be executed on a condition
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
16
JavaScript Variables
Variables are Containers for Storing Data.
JavaScript Variables can be declared in 4 ways:
19
JavaScript Const
The const keyword was introduced in ES6 (2015)
Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
20
Difference Between var, let and
const
Scope Redeclare Reassign
var No Yes Yes
let Yes No Yes
const Yes No No
22
JavaScript Operators
JavaScript Arithmetic Operators
Arithmetic Operators are used to perform arithmetic on numbers.
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
23
JavaScript Operators
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
Operator Example Same As
= 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
24
JavaScript Operators
JavaScript Comparison Operators
JavaScript comparison operators are used to compare two values
and return a Boolean value (true or false).
Operator Description
== (Equality) Compares two values for equality. e.g. (5 == '5’) returns true.
=== (Strict Equality) Compare both value and type equality. e.g. (5 === '5’ ) returns
false.
!= (Inequality) Compares two values for inequality. e.g. (5 != '5’ ) returns false.
!== (Strict Inequality) not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? Ternary(conditional) Syntax: condition ? expressionIfTrue : expressionIfFalse
operator. 25
JavaScript Operators
JavaScript String Comparison
All the comparison operators above can also be used on strings.
let text1 = "A";
let text2 = "B";
let result = text1 < text2; //return true
Note that strings are compared alphabetically.
JavaScript String Addition (+)
The + can also be used to add (concatenate) strings.
let text1 = "John";
let text2 = “Abel";
let text3 = text1 + " " + text2;
26
JavaScript Operators
JavaScript Logical Operators
JavaScript logical operators are used to combine multiple Boolean
expressions or values and return a Boolean result.
Operator Description
&& (logical and) Returns true if both expr1 and expr2 are true; otherwise,
returns false
|| (logical or) Returns true, if either expr1 or expr2 is true; if both are false,
it returns false.
! (logical not) Returns true, if expr is false; otherwise, returns false.
27
JavaScript Operators
JavaScript Type Operators
JavaScript type operators are used to determine and manipulate the
data types of values.
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
28
JavaScript Operators
JavaScript Bitwise Operators
JavaScript bitwise operators perform operations on the binary
representations of numbers.
Operator Name Description
& AND Compare the corresponding bit and If both bits are 1, the resulting bit is
1; otherwise, it's 0. Example: 5 & 3 returns 1.
| OR If at least one of the bits is 1, the resulting bit is 1; otherwise, it's 0.
Example: 5 | 3 returns 7.
~ NOT Performs a bitwise NOT operation on a single operand, inverting all bits.
Example: ~5 returns -6.
^ XOR If the bits are different, the resulting bit is 1; if they are the same, it's 0.
Example: 5 ^ 3 returns 6.
<< left shift Shifts the bits of the first operand to the left by the number of positions
specified by the second operand. Example: 5 << 1 returns 10.
>> right shift Shifts the bits of the first operand to the right by the number of positions
specified by the second operand. Example: 5 >> 1 returns 2.
29
JavaScript Data Types
String: Represents textual data, enclosed within single quotes (' ') or
double quotes (" ").
Number: Represents numeric values, including integers and floating-
point numbers.
Bigint: is used to perform operations on integers larger than 2^53-1.
Boolean: Represents a logical value, either true or false.
Undefined: Represents a variable that has been declared but has not
been assigned a value.
Null: Represents the intentional absence of any object value.
Object: Represents a collection of key-value pairs. Objects can be
created using object literals {}, constructor functions, or the Object
constructor.
The object data type can contain: An object, An array, A date(function) 30
JavaScript Data Type Example
// Numbers
let length = 16; let weight = 7.5;
// Strings
let color = “Abrham"; let lastName = “Ahmed";
// Booleans
let x = true; let y = false;
// undefined
let x; // Now x is undefined
//BigInt
let x = BigInt("123456789012345678901234567890");
// Object
const person = {firstName:"John", lastName:"Doe"};
// Array object
const cars = ["Saab", "Volvo", "BMW"];
// Date object
const date = new Date("2022-03-25");
let myVariable = null; // Null object 31
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).
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).
The parentheses may include parameter names separated by commas: (parameter1,
parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
Syntax: function name(parameter1, parameter2, parameter3) {
// code to be executed } 32
Cont.…
The () Operator
The () operator invokes (calls) the function.
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius(77);
Accessing a function with incorrect parameters can return an
incorrect answer.
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius(); // NaN
33
Cont.…
Accessing a function without () returns the function and not the
function result.
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
} let value = toCelsius;
// Output: function toCelsius(f) { return (5/9) * (f-32);
toCelsius refers to the function object, and toCelsius() refers to the
function result.
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
// code here can NOT use carName
function myFunction() {
let carName = "Volvo"; // code here CAN use carName
} // code here can NOT use carName
34
Function Expressions
A JavaScript function can also be defined using an expression. A
function expression can be stored in a variable.
const x = function (a, b) {return a * b};
let z = x(4, 3);
After a function expression has been stored in a variable, the
variable can be used as a function.
The function above is actually an anonymous function (a function
without a name).
Functions stored in variables do not need function names. They are
always invoked (called) using the variable name.
35
Self-Invoking Functions
A self-invoking expression is invoked (started) automatically,
without being called.
Function expressions will execute automatically if the expression is
followed by ().
add parentheses around the function to indicate that it is a function
expression(self-invoking function).
(function () { (function myFunction(a, b) {
let x = "Hello myself!!"; document.write(a*b);
document.write(x); //output: 200
//output:Hello myself })(10,20);
})();
//anonymous self-invoking function //normal Self-Invoking Function
36
Arrow Functions
Arrow functions allows a short syntax for writing function
expressions.
You don't need the function keyword, the return keyword, and
the curly brackets.
// ES5 //ES6
var x = function(x, y) { const x = (x, y) => {
return x * y; return x * y
} };
// ES6 document.write(x(5, 4));//20
const x = (x, y) => x * y;
document.write(x(5,4));// 20
you can only omit the return keyword and the curly brackets if
the function is a single statement.
37
JavaScript Function Parameters &
Arguments
Function parameters are the names listed in the function
definition.
Function arguments are the real values passed to (and received
by) the function.
Function Parameter Rules
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.
If a function is called with missing arguments (less than declared), the missing
values are set to undefined (NaN).
Syntax: function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
38
Function Rest Parameter (…)
The rest parameter (...) allows a function to treat an indefinite
number of arguments as an array.
function sum(...args) {
let sum = 0;
for (let arg of args)
sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
Console.log(x);//326
39
JavaScript Object
In JavaScript, an object is a collection of properties, where each property is defined as a key-
value pair.
The keys are strings , and the values can be of any type, including other objects, functions,
arrays, numbers, strings, and booleans.
You can create an object in JavaScript using several methods:
1. JavaScript Object Literal
An object literal is a list of property written as name : value pairs inside curly braces {},
separted by commas.
const person = { name: 'John',
age: 30,
greet: function() {
console.log('Hello!');
}
};
40
JavaScript Object….
2. Using the Object Constructor:
Create an empty JavaScript object using new Object(), and
add properties.
const person = new Object();
person.name = 'John';
person.age = 30;
person.greet = function() {
console.log('Hello!’);}
};
41
Accessing Object Properties
You can access object properties using dot notation or
bracket notation.
console.log(person.name); // Dot notation
console.log(person['age']); // Bracket notation
Adding and Modifying Properties
You can add or modify properties of an object dynamically:
delete person.email;
42
4
3
JavaScript if Statement
44
4
5
Example
<html>
<body>
<p>This example demonstrates the If statement.</p>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("<b>Good morning</b>");
}
</script>
<p>If the time on your browser is less than 10, you will get a
"Good morning" greeting.</p>
</body>
</html>
45
4
6
Example
<html>
<body>
<p>This example demonstrates the If…else statement.</p>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("<b>Good morning</b>"); }
else{
document.write("<b>Good Afternoon</b>"); }
</script>
<p>If the time on your browser is less than 10,
you will get a "Good morning" greeting.
Otherwise you will get a "Good Afternoon" greeting.</p>
</body>
</html>
47
4
8
Example
<html>
<body>
<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time<10){
document.write("<b>Good morning</b>");
}
else if (time>=10 && time<16){
document.write("<b>Good Afternoon</b>");
}
else{
document.write("<b>Hello World!</b>");
}
</script>
<p>
This example demonstrates the if..else if...else statement.</p>
</body>
</html>
49
5
0
Example
<script type="text/javascript">
switch (new Date().getDay())
{
case 0: day = "Sunday";
break;
case 1:day = "Monday";
break;
case 2: day = "Tuesday";
break;
case 3: day = "Wednesday";
break;
case 4: day = "Thursday";
break;
case 5: day = "Friday";
break;
case 6: day = "Saturday";
break;
}
document.write(new Date().getDay()); //return the day in number starts from Sunday to 0.
document.write("<br>"+day);
</script>
51
5
2
JavaScript Loops
A program loop is a set of instructions that is executed
repeatedly.
Loops execute a block of code a specified number of times
or while a specified condition is true.
There are two types of loops:
For: loops through a block of code for a specified
52
5
3
Example
<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is heading " + i);
document.write("</h" + i + ">");
}
</script>
</body>
</html>
54
5
5
Example 2
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
text = "";
for (var i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html> 55
5
6
Example 3
<html>
<body>
<table border="1px">
<tr>
<script>
for(var num=1; num<=5; num++){
document.write("<td>"+ num +"</td>");
}
</script>
</tr>
</table>
</body>
</html>
56
5
7
for in loop
for/in - loops through the properties of an object
E.g Syntax:
<html> for (key in object) {
<body> // code block to be executed
<p id="demo"></p> }
The for in loop iterates over
<script> a person object
var txt = ""; var key; Each iteration returns a key
var person = { fname: "Sam", The key is used to access the value of
lname: "Abebe", the key
The value of the key is person[key]
age: 25 };
for (key in person) {
txt += person[key] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script> </body> </html>
58
5
9
Example
<html>
<body>
<table border="1px">
<tr>
<script>
var num=1;
while(num<=5){
document.write("<td>"+ num +"</td>");
num++;
}
</script>
</tr>
</table></body>
</html> 61
6
2
Example 2
<html>
<body>
<table border="1px"> <tr><script>
var rownum=1, colnum=1;
while(rownum<=3) {
document.write("<tr>");
while(colnum<=4){
document.write("<td>"+ rownum + "," + colnum +"</td>");
colnum++;
}
document.write("</tr>");
rownum++; colnum=1;
}</script></tr></table></body></html>
62
6
3
Javascript Arrays
JavaScript arrays are used to store multiple values in a single
variable(an ordered collection of values referenced by a single
variable name).
Syntax:
Using the JavaScript new keyword
Example
<body><script>
var MonthTxt=[ "January", "February", "March", "April", "May","June", "July",
"August", "September", "October", "November", "December“];
document.write("<h3>"+" Months of the year are:"+"</h3>");
document.write("<ul>");
for (var i = 0; i < MonthTxt.length; i++) {
document.write("<li>"+MonthTxt[i] + "</li>");
}
document.write("</ul>");
</script>
</body>
// we can use array() or array[] in array declaration and assignment
65
6
6
68
DOM Tree Structure
It used to access objects in web pages with javascript .
69
DOM manipulation with
JavaScript
“DOM manipulation”, it simply means changing the DOM (the
HTML document). This in turn means, changing the HTML
elements, that DOM converted into objects.
Manipulating DOM involves two steps:
70
DOM manipulation with
JavaScript…
Selecting in JavaScript can also be divided into three types
1. Select an individual element:
• Example: Finding one specific <div> element
2. Select multiple elements:
Example: • Finding all <div> elements
3. Traversing between multiple elements:
• Example: Finding a <p> element within a particular <div>
71
DOM manipulation: selecting an
individual element
There are three common methods to select one specific element.
1.getElementById() method: it accepts CSS’ id selector as its
argument and returns an element whose id matches the passed
string/id.
2.querySelector() method: it takes CSS selectors as its argument and
returns the first element that matches the passed selector. Meaning, the
method can take ids, classes and tag names as its argument. Example
» document.querySelector("#hi"); // selects the element with “hi” id name
» document.querySelector(".bye"); // selects all elements with “hi” class name, but
returns first element in the document with class name
73
DOM manipulation: Selecting
multiple elements…..
Selecting one element from a nodeList: querySelectorAll() method
a. Selecting using the item() method :
▪ var el = document.querySelectorAll(".yellow");
▪ el.item(0);// selects the first li with yellow class
▪ el.item(1);// selects the 2nd li with yellow class
b. Selecting using array syntax:
▪ var el = document.getElementsByClassName("red");
▪ console.log(el[1]); //selects the 2nd li with red class
74
DOM manipulation: Selecting
multiple elements…..
2. getElementsByTagName() method: The method takes a tag name
and returns a collection of all elements in the document with the
specified tag name, as an HTMLCollection object.
Syntax: document.getElementsByTagName(tagname)
getElementsByTagName("li")); //returns HTMLCollection with all <li>
Selecting one element from an HTMLCollection:
var el = document.getElementsByTagName("li");
console.log(el.item(0));// returns the 1st li element
console.log(el[1]); // returns the 2nd li element
75
DOM manipulation: Selecting
multiple elements…..
3. getElementsByClassName(): Just like getElementsByTagName(),
this method also returns a live HTMLCollection representing an array-
like object of all elements with the specified class name.
Syntax: document.getElementsByClassName(classname)
getElementsByClassName(“red”)// returns HTML collection with all
elements having the “red” class
• Selecting one element from an HTMLCollection:
var el = document.getElementsByClassName("red");
console.log(el[1]); //selects the 2nd li element with red class
console.log(el.item(0));// selects the 1st li element with red
class
76
Selecting elements (traversing
between multiple elements)
Traversing between multiple elements: Traversing is the act of
selecting an element from another/neighboring element.
Traversing directions: we can traverse in three directions:
a.Traversing downwards:
b.Traversing upwards:
c.Traversing sideways:
78
Selecting elements (traversing
between multiple elements)
methods….
b. Traversing upwards:
parentElement(): parentELement is a property that lets you
select the parent element.
parentElement is great for selecting one level upwards.
console.log(document.getElementById("one").parentElement);
//prints the <ul> which is the parent to all the <li>
80
Altering values (working with
HTML content)
Altering HTML content: change the content of HTML
elements.
Meaning, we can add, update or remove the HTML tag, the
text content in an HTML element, or the entire block of
HTML code from your page.
81
Altering values (working with
HTML content)
createElement() method: it creates an Element Node with the
specified element name.
• Syntax: document.createElement(nodename).
<div id="bigId">
<div>Hello</div>
<ul id="listOfFruits">
<li id="one" class="red">Apple</li>
<li id="two" class="yellow">Mango</li>
</ul>
Let’s create a new <li> and insert it as the last child of our <ul>
</div>
var liElem = document.createElement("li");
82
Altering values (working with
HTML content)
appendChild() method: it appends a set of node objects as
the last child of a node. See the above example.
Syntax: node.appendChild(node)
Let’s create a new <li> and insert it as the last child of our <ul>
83
Altering values (working with
HTML content)
prepend () method: it inserts a set of node objects before
the first child of the Element.
Syntax: node. prepend(node)
Let’s insert an <li> as the first child of our <ul>
var liElem2 = document.createElement("li");
var parent = document.getElementById("listOfFruits");
parent.prepend(liElem2);
console.log(parent);// shows that a new <li> is added as
the first child of the parent node (the <ul>)
84
Altering values (working with
HTML content)
innerHTML() method: it changes or prints the HTML
content (inner HTML) of an element.
Syntax: HTMLElementObject.innerHTML
Let’s change the inner HTML of our <div> with " bigId " id
var content = document.getElementById(" bigId ");
content.innerHTML = "<li>Kiwi</li>";
console.log(content.innerHTML);// now prints <li>Kiwi</li>
85
Altering values (working with
HTML content)
textContent() method: it changes or returns the text content of
the specified node, and all its descendants.
TextContent() returns all text contained by an element and all its
children.
Syntax: node.textContent
Let’s change the text content of our <div> that has "bigId" as its id
var content = document.getElementById("bigId");
console.log(content.textContent);// prints “hello”, “apple”, and
“mango”
content. textContent = "New text here";
console.log(content.textContent);// prints "New text here"
86
Altering values (working with
HTML content)
removeChild() method: it removes a specified child node of the
specified element.
Note: Use the appendChild() or insertBefore() methods if you want to
insert the removed node back into the same document.
Syntax; removeChild(child);
Let’s remove the <li> child from our <ul>
87
Altering values (working with
HTML attribute)
This is when you want to add, change or remove the attribute value
of an element.
89
Altering values (working with
HTML attribute) methods
ClassList() method: The classList property returns the class name(s)
of an element.
This property can be used to add, remove and toggle CSS classes on
an element.
Syntax: element.classList
Let’s add a class name for our last name <input> and print the
added class name
Var classForLastName= document.getElementsByName("lastName")[0];
classForLastName.classList.add("myLastName");// adds class name
console.log(classForLastName.classList);// prints added class
classForLastName.classList.toggle(“myname”); // add if there is no class or
remove if there is a class name “myname”.
90
Altering values (working with
HTML attribute) methods
Id property: The id property sets or returns the id of an
element (the value of an element's id attribute).
• Syntax: HTMLElementObject.id
• Let’s print the id for our <form> element
var myForm = document.getElementById("formID");
console.log(myForm.id); // prints the id name "formID"
91
Altering values (working with
HTML attribute) methods
Id property: The id property sets or returns the id of an
element (the value of an element's id attribute).
• Syntax: HTMLElementObject.id
• Let’s print the id for our <form> element
var myForm = document.getElementById("formID");
console.log(myForm.id); // prints the id name "formID"
92
Altering values (working with
HTML attribute) methods
hasAttribute() method: it returns a Boolean value (true or
false) indicating whether the specified element has the
specified attribute or not.
• Syntax: element.hasAttribute(attributename)
var myForm = document.getElementById("formID");
console.log(myForm.hasAttribute("name"));
// prints false because the <form> element doesn't have a name
attribute
console.log(myForm.hasAttribute("id"));
//prints true because <form> element has id attribute.
93
Altering values (working with
HTML attribute) methods
getAttribute() method: it returns the value of the attribute
of an element.
• Syntax: element.getAttribute(attributename
var firstInputVal = document.getElementsByTagName("input")[0];
console.log(firstInputVal.getAttribute("name"));
// returns "firstName" which is the value of the "name" attribute for
first name <input>
94
Altering values (working with
HTML attribute) methods
setAttribute() method: it adds the specified attribute to an
element and gives it the specified value.
If the specified attribute already exists, only the value is
set/changed. Otherwise, a new attribute is added with the
specified name and value.
Syntax: element.setAttribute(attributename, attributevalue)
var firstInputVal =
document.getElementsByTagName("input")[0];
firstInputVal.setAttribute(" value ", " first name ");
// placeholder input value of “first name” added to our <input>
95
Altering values (working with
HTML attribute) methods
removeAttribute() method: it removes the specified
attribute from an element.
Syntax: element.removeAttribute(attributename)
var firstInputVal = document.getElementsByTagName("input")[0];
firstInputVal.removeAttribute("type");
// removes the “type” attribute
console.log(firstInputVal.getAttribute("type"));
// returns null because we just removed the "type" attribute
96
Altering values (working with
inline styling)
Changing CSS Values with the style property
Syntax:
• To return style properties: = element.style.property
• To set/add style properties: = element.style.property = value
<h1 id="title">Fruits</h1>
<div class="containerDiv" id="divID">
<ul id="listOfFruits" class="Kelele">
<li id="one" class="red">Apple</li>
<li id="two" class="yellow">Mango</li>
</ul>
</div>
97
Altering values (working with
inline styling) property….
Style color property: The color property sets or returns the
color of the text.
• Let’s add “red” color to the text of the first <li>
var firstLi = document.getElementById("one");
firstLi.style.color = "red"; // changes text color of <li> to red
console.log(firstLi.style.color);// prints "red"
98
Altering values (working with
inline styling) property….
Style font property: The font property sets or returns
separate font properties.
Let’s add font (font-weight, font-size and font-family) to
our 2nd <li> and print the font values we just added
var secondLi = document.getElementById("two");
secondLi.style.font = "bold 30px arial";
// changes text font of 2nd <li>
console.log(secondLi.style.font); // prints "bold 30px arial"
99
Altering values (working with
inline styling) property….
background color property: The backgroundColor
property sets or returns the background color of an element.
Let’s change the background color of 2nd <li> into yellow
and print the changed color
var secondLi = document.getElementById("one");
secondLi.style.backgroundColor = "yellow"; // changes the
background color of 2nd <li>to yellow
console.log(secondLi.style.backgroundColor); // prints "yellow"
100
Altering values (working with
inline styling) property….
Style display property: The display property sets or returns
the element's display type. Elements are mostly block or
inline. You can also hide the element using display:none
Let’s change the display property of our <li> into none and
print the changed display
var h1Element = document.getElementById("title");
h1Element.style.display = "none"; // hides our <h1>
console.log(h1Element.style.display); // prints "none" because we just
hid our <h1> above
101
Altering values (working with
inline styling) property….
Style border property: The border property sets or returns
up to three separate border properties.
Let’s change the border property of our <div> into thick,
solid, and red and print the properties.
102
Altering values (working with
inline styling) property….
Style border property: The border property sets or returns
up to three separate border properties.
Let’s change the border property of our <div> into thick,
solid, and red and print the properties.
103
JavaScript events
Events in JavaScript are what happens on the browser when
a user browses/manipulates a any website.
Common Event types
A. UI/Window events
B. Key board events
C. Mouse events
D. Form Events
104
A. UI/Window events
105
C. Mouse events
D. Form Events
106
Event Handling
It is a mechanism that controls these events and decides what
should happen when an event happens.
When a user interacts with any HTML element on a web page,
there are three steps involved in triggering a script associated with
an event:
1. Selecting an element: The element is selected to bind it with the
event handler (JavaScript function) when an event occurs on it
2. Binding an event on the selected element: This is to identify the
specific event that will trigger the event handler to execute.
3. Attach a script: This is to instruct the web browser which specific
event handler to execute when a specific event happens.
107
Ways to bind an event
There are three ways to assign/bind event handlers to an event:
1. HTML event handlers attribute: HTML allows event handler
attributes, with JavaScript code, to be added to HTML elements.
Syntax: onclick="changeBackground()“
function showClickedAlert() { function changeButtonColor() {
alert("button clicked!!"); var myButton =
} document.getElementById("buttonId");
//Attaching the event handler function myButton.style.color = "red";
when there is a click event on our }//Attaching the event handler function
<button> element: when there is a click event on our
<button <button> element:
onclick="showClickedAlert()">Save</ <button id="buttonId"
button> onclick="changeButtonColor()">Chan
ge Color</button>
108
2. Traditional DOM event handlers:
when a user interacts with the DOM object, there are 3 Steps
involved
▪ First, select the element you want to bind an event with
▪ Then bind the element with the event handler
▪ Finally attach the event handler function on the event
Syntax:
element.onevent = functionName;
109
Traditional DOM event handler example
Example 1: Let’s try to change the text color of a <button> to red
when a user clicks on the <button>
Selecting the <button> we want to bind the event (click) with
113
Adding multiple listeners for a single event:example
Let’s add different event handler functions and change the text
color of button to red, change the button’s background to yellow
and alert a message that says, "button clicked!!!“
var myButton = document.getElementById("buttonId");
myButton.addEventListener("click", function () {
myButton.style.color = "red";
});
myButton.addEventListener(“dbclick", function () {
alert("button clicked!!!");
});
myButton.addEventListener(“mouseover", function () {
myButton.style.backgroundColor = "yellow";
});
114
Halting default behaviors
There are scenarios where you want the default HTML behavior
not to take effect on the browser.
For example, you don't want the submit button to submit the form
when required filled are not filled out.
The preventDefault() method: It tells the user agent that if the
event does not get explicitly handled, its default action should not
be taken as it normally would be.
Syntax:
event.preventDefault();
115
preventDefault() method example….
By default, the submit event fires when the user clicks a submit
button (<button> or <input type="submit">) or presses Enter while
editing a field.
<form id="formID">
<button id="buttonId" type="submit">Submit here</button>
</form>
Now let’s prevent the form from being submitted and change the <button>’s text to
“Form submission prevented” on submit event
var myForm = document.getElementById("formID");
var myButton = document.getElementById("buttonId");
function functionToPrevent(event) {
myButton.innerHTML = "Form submission prevented";
event.preventDefault();
} myForm.addEventListener("submit", functionToPrevent);
116
1
1
7
Data validation in
JavaScript……
function validateForm() {
// Get form elements
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let age = document.getElementById("age").value;
// Validate name
if (name === "") {
alert("Name must be filled out");
return false;
} // Validate email
if (email === "") {
alert("Email must be filled out");
return false;
} // Validate age
if (age === "") {
alert("Age must be filled out");
return false;
} else if (isNaN(age) || age <= 0) {
alert("Please enter a valid age");
return false;
}} 118
1
1
9
Example
<html><head>
<script type="text/javascript">
function validate(){
if( document.myForm.fName.value == "" ){
alert( "Please provide your First name!" );
document.myForm.fName.focus() ;
return false;}
if( document.myForm.lName.value == "" ){
alert( "Please provide your Last name!" );
document.myForm.lName.focus() ;
return false; }
if( document.myForm.email.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;}
return(true);} </script> </head> 119
1
2
0
<body>
<H3> Student Registration Form </H3>
<form action="registration.php" name="myForm"
onsubmit="return(validate());">
<p>First Name:<input type="text" name="fName" /></p>
<p>Father Name:<input type="text" name="lName" /></p>
<p>Email Address:<input type="text" name="email" /></p>
<p>Phone Number:<input type="text" name="phone"/></p>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form></body></html> 120
e E n d
T h
121