0% found this document useful (0 votes)
18 views

Chapter 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Chapter 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 81

Chapter Four

Client-side programming – JavaScript (JS)

By: Behayilu M.
Faculty of Computing and Software Eng.,
Arba Minch Institute of Technology(AMiT),
Arba Minch University
Web design and programming 1
Contents

• Introduction
• Language Format
• Variables
• Functions in JavaScript
• DOM
• Event handlers
• Form validation

Web design and programming 2


What is JavaScript?
• a lightweight programming language ("scripting language")
• used to make web pages interactive
• insert dynamic text into HTML (ex: user name)
• react to events (ex: page load, user click)
• get information about a user's computer (ex: browser type)
• perform calculations on user's computer (ex: form validation)
• a web standard (but not supported identically by all browsers)
• NOT related to Java other than by name and some syntactic similarities
Web design and programming 3
…cont’d
Why Study JavaScript?
 JavaScript is one of the 3 languages all web developers must learn:
HTML
( Structure )
• HTML to define the content of web pages

• CSS to specify the layout of web pages

• JavaScript to program the behavior of web pages

CSS JavaScript
( Style ) ( Behavior )

Web design and programming 4


The <script> Tag
• In HTML, JavaScript code is inserted between <script> and </script> tags.

• <script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

• Can be placed in the head, body, inline with html element ,as you like.
myScript.js
• But code separation is advised (content – presentation – behavior )
function sum(a,b )
{
• Use the following tag in – html to link external console.log(a+b);
}
• <script src="myScript.js"></script>
• External scripts are practical when theWeb
same code
design and is used in many different web pages. 5
programming
External JavaScript Advantages
Placing scripts in external files has some advantages: <!DOCTYPE html>
<html>
• It separates HTML and code <body>

• It makes HTML and JavaScript easier to read <h2>Demo External JavaScript</h2>

<p id="demo">A Paragraph.</p>


and maintain
<button type="button" onclick="myFunction()">Try
• Cached JavaScript files can speed up page loads it</button>

To add several script files to one page use several <p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
script tags
<script src="myScript.js"></script>
Example </body>
</html>
• <script src="myScript1.js"></script>
Recommended to external JS here before </body>
Web design and programming 6
• <script src="myScript2.js"></script>
What JavaScript can do?
• JavaScript Can Change HTML Content

document.getElementById("demo").innerHTML = "Hello JavaScript";

• JavaScript Can Change HTML Attribute Values

<button onclick="document.getElementById('myImage').src=‘dog.gif'"> Change</button>

• JavaScript Can Change HTML Styles (CSS)

document.getElementById("demo").style.fontSize = "35px";

• JavaScript Can Hide HTML Elements

document.getElementById("demo").style.display = "none";

• JavaScript Can Show HTML Elements


7
document.getElementById("demo").style.display = "block";
Web design and programming
Displaying messages( outputs )
<!DOCTYPE html>
• JavaScript can "display" data in different ways: <html> My First Web Page
<body> My First Paragraph.
Writing into an HTML element, using innerHTML.
<h1>My First Web Page</h1> 11
Writing into the HTML output using document.write(). <p>My First Paragraph</p>
<p id="demo"></p>
Writing into an alert box, using window.alert().
<script>
Writing into the browser console, using console.log(). document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
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

 Changing the innerHTML property of an HTML element is a common way to display data in HTML. 8
Web design and programming
Displaying messages( outputs )
Using document.write()
• Using document.write() after an HTML document is loaded, will delete all existing HTML:

<p>My first paragraph.</p> <p>My first paragraph.</p>


<script> <button type="button"
My first paragraph. onclick="document.write(5 + 6)">Try 11
document.write(5 + 6);
11 it</button>
</script>

Using window.alert() <script>


window.alert(5 + 6);
• You can use an alert box to display data: </script>

• In JavaScript, the window object is the global scope object, that means that variables,
properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional. 9
Web design and programming
Displaying messages( outputs )
Using console.log()
• For debugging purposes, you can call the console.log() method in the browser to display data.
• Displays message in the browsers console- not visible on the web page.

<script> 11
console.log(5 + 6);
</script>
JavaScript Print

• JavaScript does not have any print object or print methods. <button
onclick="window.print()">Print this
• You cannot access output devices from JavaScript. page</button>

• The only exception is that you can call the window.print() method in the browser to print the
content of the current window. Web design and programming 10
Displaying messages( outputs )
• confirm(message)
• Generates a message on pop up

window with two options , yes or no

• prompt(message)

• Displays a message on pop up window

to notify user for input

Web design and programming 11


JavaScript Variables
What are Variables?
• Variables are containers for storing data (storing data values).
There are 4 ways to declare a JavaScript Variable:
let x=8, y=7, sum;
1. Using var : var x = 5; {
sum = x + y;
let x=5;
2. Using let : let x = 5; // x can be used here console.log(sum);
}
3. Using const : const price = 5; // x can not be used here 15
4. Using nothing : x = 5;
• Always declare JavaScript variables with var, let, or const. function varTest( )
• If you want your code to run in older browser, you must use var. { var x=5;
{ var x=10’// same variable
• If you want a general rule: always declare variables with const. alert(x); // shows 10
}
• If you think the value of the variable can change, use let. alert(x); //shows 10
}
• JavaScript identifiers are case-sensitive.
Web design and programming
12
JavaScript Data Types
• JavaScript variables can hold different data types: numbers, strings, Booleans, objects and more:
 let length = 16; // Number
 let lastName = "Johnson"; // String
 let x = {firstName:"John", lastName:"Doe"}; // Object
 let age; // undefined
JavaScript Strings
• A string (or a text string) is a series of characters. let name = “Marta"; // Using double quotes
• Strings are written with quotes. You can use single or double quotes: // let name= ‘Dawit’;
• You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
let answer = "It's alright"; JavaScript comments
JavaScript Numbers
• JavaScript has only one type of numbers.
// single line comment
• Numbers can be written with, or without decimals:
/* Multiple line
comment
• let x1 = 34.00; // Written with decimals
Web design and programming */ 13
JavaScript Data Types
JavaScript Booleans
let name = “Marta”;
• Booleans can only have two values: true or false.
let age = 26;
let x = 5;
console.log(typeof name); // string
let y = 5; console.log(typeof age); // number
console.log(x == y) // Returns true
Undefined
• In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
let car; // Value is undefined, type is undefined
car = undefined; // Value is undefined, type is undefined
The typeof Operator
• The typeof operator returns the type of a variable or an expression:
typeof “John”; // string Web design and programming 14
JavaScript Arrays
• An array is a special variable, which can hold more than one value:
Syntax : const array_name = [item1, item2, ...];
• const cars = ["Saab", "Volvo", "BMW"];
• const cars = new Array("Saab", "Volvo", "BMW");
• For simplicity, readability and execution speed, use the array literal method.
• It is a common practice to declare arrays with the const keyword.
• Accessing Array Elements : const cars = ["Saab", "Volvo", "BMW"]; let car = cars[0];
Access the Full Array
• With JavaScript, the full array can be accessed by referring to the array name:

• const cars = ["Saab", "Volvo", "BMW"];

document.getElementById("demo").innerHTML = cars;
Array Properties and Methods
• cars.length // Returns the number of elements
Web design and programming 15
• cars.sort() // Sorts the array
JavaScript Comparison Operators
• Comparison operators compare two values and give back a boolean value: either true or false. Comparison
operators are used in decision making and loops.
Operator Description Example
== Equal to: true if the operands are equal 5==5; //true
!= Not equal to: true if the operands are not equal 5!=5; //false
5==='5';
=== Strict equal to: true if the operands are equal and of the same type
//false
Strict not equal to: true if the operands are equal but of different type or not equal
!== 5!=='5'; //true
at all
> Greater than: true if the left operand is greater than the right operand 3>2; //true

Greater than or equal to: true if the left operand is greater than or equal to the
>= 3>=3; //true
right operand

< Less than: true if the left operand is less than the right operand 3<2; //false
Less than or equal to: true if the left operand is less than or equal to the right
<= 2<=2; //true
operand Web design and programming
16
…cont’d

Example 1: Equal to Operator


Example 2: Not Equal to Operator
const a = 5, b = 2, c = 'hello';
const a = 3, b = 'hello';
// equal to operator
// not equal operator
console.log(a == 5); // true
console.log(a != 2); // true
console.log(b == '2'); // true
console.log(b != 'Hello'); // true
console.log(c == 'Hello'); // false • != evaluates to true if the operands are not equal.
• == evaluates to true if the operands are equal.

Example 3: Strict Equal to Operator Example 4: Strict Not Equal to Operator


const a = 2; const a = 2, b = 'hello';

// strict equal operator // strict not equal operator


console.log(a === 2); // true console.log(a !== 2); // false
console.log(a === '2'); // false console.log(a !== '2'); // true
• === evaluates totrue if the operands are equal console.log(b !== 'Hello'); // true
and of the same type. • !== evaluates to true if the operands are strictly not
equal. It's the complete opposite of strictly equal ===.

Note: The difference between = = and = = = is that: = = evaluates to true if the operands are equal, however, = =
Web design and programming 17
= evaluates to true only if the operands are equal and of the same type.
JavaScript Math Object
• The JavaScript Math object allows you to perform Math.sqrt()
mathematical tasks on numbers. • Math.sqrt(x) returns the square root of x:

• Math.PI; // returns 3.141592653589793 Math.sqrt(64); // returns 8

Math.round() Math.ceil()
• Math.round(x) returns the value of x rounded to its • Math.ceil(x) returns the value of x
nearest integer: rounded up to its nearest integer:

Math.round(4.7); // returns 5 • Math.ceil(4.4); // returns 5


Math.round(4.4); // returns 4 Math.floor()
Math.pow() • Math.floor(x) returns the value of x
• Math.pow(x, y) returns the value of x to the power of y: rounded down to its nearest integer:
Web design and programming 18
Math.pow(8, 2); // returns 64 • Math.floor(4.7); // returns 4
JavaScript Random
Math.random()

• Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):

document.getElementById("demo").innerHTML = Math.random(); // 0.25396137169360156

• Math.random() used with Math.floor() can be used to return random integers.


<!DOCTYPE html>
// Returns a random integer from 0 to 9: <html>
<body>
Math.floor(Math.random() * 10); <h2>JavaScript Math</h2> 37
<p id="demo"></p>
<script>
// Returns a random integer from 1 to 10: document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100) + 1;
Math.floor(Math.random() * 10) + 1; </script>
</body>
</html>
Web design and programming 19
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).
• A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Syntax: function name(parameter1, parameter2, parameter3) {
// code to be executed
}
• Function parameters are listed inside the parentheses () in the function definition.
• Function arguments are the values received by the function when it is invoked.
Function Invocation
• The code inside the function will execute when "something" invokes (calls) the function:
• When an event occurs (when a user clicks a button) function myFunction(p1, p2) {
return p1 * p2; // The function returns the
• When it is invoked (called) from JavaScript code product of p1 and p2
•document.getElementById("demo").innerHTML }
Automatically (self invoked) = myFunction(4, 3); 20
JavaScript Functions
• There are 3 ways of writing a function in JavaScript: 2. Function Expression: Function Expression is
another way to define a function in JavaScript. Here we
1- Function Declaration: Function Declaration is the
define a function using a variable and store the returned
traditional way to define a function.
value in that variable.
• It is somehow similar to the way we define a function in
other programming languages. / Function Expression

/ Function declaration const add = function(a, b) {


function add(a, b) { console.log(a+b);
console.log(a + b);
}
}
// Calling function
// Calling a function
add(2, 3);
add(2, 3);
Web design and programming // 5 21
JavaScript Functions
Note: When there is a need to include multiple
3. Arrow Functions: Arrow functions are been
lines of code we use brackets.
introduced in the ES6 version of JavaScript.
• Also, when there are multiple lines of code in
• It is used to shorten the code. ‘Here we do
the bracket we should write return explicitly
not use the “function” keyword and use the
to return the value from the function.
arrow symbol.
// Multiple line of code
// Single line of code const great = (a, b) => {
if (a > b)
let add = (a, b) => a + b;
return "a is greater";
console.log(add(3, 2)); else
return "b is greater";
// 5
} 22
Web design and programming
JavaScript Objects
• In JavaScript objects are variables too. But objects can contain many values.

• This code assigns many values (John, Doe, 50,blue) to a variable named person:

• const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

• The name:values pairs in JavaScript objects are called properties:

• It is a common practice to declare objects with the const keyword.

• Accessing Object Properties


• objectName.propertyName or

• objectName["propertyName"]

• person.lastName; // Doe
Web design and programming 23
• person["lastName"];
Object Methods
• Objects can also have methods.
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
• In this example below, this refers to the person object.
• Accessing Object Methods const person = {
• You access an object method with the firstName: "John",
following syntax: objectName.methodName( ) lastName : "Doe",
name = person.fullName(); id : 5566,

• If you access a method without the () fullName : function() {

parentheses, it will return the function definition: return this.firstName + " " + this.lastName;
}
name = person.fullName;
};
Web design and programming 24
JavaScript Date Objects
• By default, JavaScript will use the browser's time zone and display a date as a full text string:
const d = new Date();
Fri Apr 15 2022 13:47:55 GMT+0200 (Eastern European
document.getElementById("demo").innerHTML = d; Standard Time)
• JavaScript Get Date Methods
Method Description const d = new Date();
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31) d.getFullYear(); // 2022
getHours() Get the hour (0-23) d.getMonth() + 1; // 4
getMinutes() Get the minute (0-59)
d.getDate(); //15
d.getHours(); //13
getSeconds() Get the second (0-59) d.getMinutes(); //1
getMilliseconds() Get the millisecond (0-999) d.getSeconds(); //23
d.getMilliseconds(); //639
getTime() Get the time (milliseconds since January 1, 1970)

getDay() Get the weekday as a number (0-6)


Date.now() Get the time. ECMAScript 5. 25
Web design and programming
Document Object Model (DOM)
• When a web page is loaded, the browser creates a Document Object Model of the page.
<!DOC TYPE html>
• Treats all HTML elements as objects. <html>
<head>
• It is a w3c standard for how to :
<title>The Text </title>
 Get </head>
<body>
 Change <h1>My Header</h1>
 Add or <p> My Paragraph</p>
</body>
 Delete HTML elements </html>

• The HTML DOM is a standard object model and programming interface for HTML. It defines:
 The HTML elements as objects

 The properties of all HTML elements

 The methods to access all HTML elements

 The events for all HTML elements


26
• Therefore, The DOM is a ‘tree structure’ representation of an HTML structure.
Web design and programming
Document Object Model (DOM)

Web design and programming 27


DOM element objects
• The DOM is a JavaScript representation of a webpage.

console.dir(icon);

• Output the list of object properties

Web design and programming 28


JavaScript DOM Selectors
• With JavaScript, we can select any element from the DOM tree using the document object.
Why do we select elements?
<!DOC TYPE html>
 To get their content
<html lang=“en”>
 To change their content <head>
 To style them <title>The Text </title>
 To get or change their attribute </head>
<body>
 To remove them <h1>My Header</h1>
 And many more… <p> My Paragraph</p>
<script>
Select the Topmost Elements alert(document.documentElement.getAttribute("lang"));
• The topmost elements can be selected directly from alert(document.head.firstElementChild.innerHTML);
the document object properties. document.body.style.backgroundColor ="green";
</script>
• document.documentElement selects <html>
</body>
• document.head. Selects <head> </html>
• document.body. Selects <body>
Web design and programming 29
JavaScript DOM Selectors
Select an Element By ID

• The document.getElementById() selects the element whose id attribute matches the


specified string.

• It is the best method to use when selecting a single element.

• The easiest way to find an HTML element in the DOM, is by using the element id.

<p id="demo"></p>
<script>
const element = document.getElementById(“demo");
element.innerHTML = “hello world”;
</script> Web design and programming 30
JavaScript DOM Selectors
Select Elements By Class Name
• The document.getElementsByClassName( ) selects all elements with the given class name.

• It returns an array of objects.

<p class="red-color">Hello World!</p>


<p>Hello World!</p>
<p class="red-color">Hello World!</p>
<script>
var x = document.getElementsByClassName("red-color"); Hello World!
for (let i = 0; i < x.length; i++) { Hello World!
x[i].style.color = "red"; Hello World!
x[i].style.fontSize ="20px";
}
</script>
Internet programming I 31
JavaScript DOM Selectors
Select Elements By Tag Name
• The document.getElementsByTagName( ) selects all elements with the given tag name.

• It returns an array of objects.

• In this example, we will style all <h2> elements.


<h2>Hello World!</h2>
<p>Hello World!</p>
<h2>Hello World!</h2> Hello World!
<p>Hello World!</p> Hello World!
<script> Hello World!
var x = document.getElementsByTagName("h2"); Hello World!
for (let i = 0; i < x.length; i++) {
x[i].style.color = "red";
x[i].style.fontSize ="20px";
}
</script> Internet programming I 32
JavaScript DOM Selectors
Select Elements By Name
• The document.getElementsByName( ) selects all elements with the given name.

• It returns an array of objects.

• In this example, we use the document.getElementsByName to select inputs by their name attributes.

​<p><label>First Name: <input type="text" name="firstName"></label></p>


<p><label>Last Name: <input type="text" name="lastName"></label></p>
<button onclick="getValues( )">Get Values</button>
<script>
function getValues() {
var firstName = document.getElementsByName("firstName")[0].value;
var lastName = document.getElementsByName("lastName")[0].value; First Name:
var fullName = "Your full name is " + firstName +" " +lastName;
Last Name:
alert(fullName);
}
</script> Get Values
Internet programming I 33
Select Elements Using CSS Selecters
• The document.querySelectorAll() selects all elements that match the specified selector.
• The selector must be a valid CSS selector.
• It returns an array of the selected elements(nodes). Selects the first match element
• In this example, the element with the demo id is selected.
<p id="demo">Lorem ipsum</p>
document.querySelectorAll("#demo")[0].innerHTML ="Hello World"; //document.querySelector(“#demo”);

• In this example, all elements with the ‘red-color’ class name are selected.
<p class="red-color">Hello World!</p>
<p>Hello World!</p>
<p class="red-color">Hello World!</p>
<script>
var x = document.querySelectorAll(".red-color");
Hello World!
for (let i = 0; i < x.length; i++) { Hello World!
x[i].style.color = "red"; Hello World!
x[i].style.fontSize ="20px";
}
Internet programming I 34
</script>
JS DOM Nodes
DOM Nodes
• In a DOM tree, every element is an object.
• For example, the document body object represents the <body> element.
What is a Node?
• A node is any object in the DOM tree.
• Therefore, a node can be any HTML elements such as <html>, <body>,
<head> and all the other elements.
• All comments are comment nodes
• With DOM, all nodes in the node tree can be accessed by JavaScript.
• New nodes can be created, and all nodes can be modified or deleted.
Node Relationships
• The nodes in the node tree have a hierarchical relationship to each other.
• The terms parent, child, and sibling are used to describe the relationships.
• In a node tree, the top node is called the root (or root node).
• Every node has exactly one parent, except the root (which has no parent)
• A node can have a number of children
35
• Siblings (brothers or sisters) are nodes with the same parent
Web design and programming
JavaScript DOM Navigation
• Navigating nodes means reaching nodes in the DOM tree.

Navigating Element Nodes


• The following document object properties are used to navigate element nodes:

• parentElement, firstElementChild, lastElementchild, children[index], previousElementSibling,


nextElementSibling.  <head> has one child: <title>

<html>  <title> has one child (a text node): "DOM


HTML left you can read:
<head> example"
<title>DOM Example</title>  <html> is the root node
 <body> has two children: <h1> and <p>
</head>  <html> has no parents
<body>  <h1> has one child: "DOM Lesson one"
 <html> is the parent of <head> and
<h1>DOM Lesson one</h1>  <p> has one child: "Hello world!"
<p>Hello world!</p> <body>
 <h1> and <p> are siblings
</body>  <head> is the first child of <html>
 DOM Example is a child of <title>
 <body> is the last child of <html>
</html> Internet programming I
 Hello world! Is a child of <p>
36
Navigating Element Nodes
Parent and Children
• The parentElement property returns the DOM node’s parent element.

• In this example, we will select the <p> element’s parent element which the <div>.

<div id="container">
<h1> Lorem Ipsum</h1>
<p id="demo"> This is simple paragraph </p>
<a href="http://example.com">Go to example.com</a>
</div>
Lorem Ipsum
<script> This is simple paragraph
Go to example.com
var pElement = document.getElementById("demo")
pElement.parentElement.style.background = "gold";
</script> Internet programming I 37
Navigating Element Nodes
• The firstElementChild property returns the DOM node’s first child element. (a)

• The lastElementChild property returns the DOM node’s last child element. (b)

<div id="container"> <div id="container">


<h1> Lorem Ipsum</h1> <h1> Lorem Ipsum</h1>
<p id="demo"> This is simple paragraph </p> <p id="demo"> This is simple paragraph </p>
<a href="http://example.com">Go to example.com</a> <a href="http://example.com">Go to example.com</a>
</div> </div>
<script> <script>
var divElement=document.getElementById("container"); var divElement = document.getElementById("container");
divElement.firstElementChild.style.background = "gold"; divElement.lastElementChild.style.background = "gold";
</script> </script>
(a) Internet programming I (b) 38
Navigating Element Nodes
• The children property returns a collection of the selected element’s children.

• The collection is like an array, therefore we can access each item using bracket notation.

• In this example we will select and style the <div> element’s second child.

<div id="container">
<h1> Lorem Ipsum</h1>
<p id="demo"> This is simple paragraph </p>
<a href="http://example.com">Go to example.com</a>
</div>
<script>
var divElement = document.getElementById("container");
divElement.children[1].style.color = "green";
</script> Internet programming I 39
Navigating Element Nodes
• The previousElementSibling property returns the previous element prior to the specified one in a parent’s
children list.

• The nextElementSibling property returns the next element prior to the specified one in a parent’s children list.

<div id="div1"> <div id="div1">


<h1> Lorem Ipsum</h1> <h1> Lorem Ipsum</h1>
<p id="demo"> This is simple paragraph </p> <p id="demo"> This is simple paragraph </p>
<a href="http://example.com">Go to example.com</a> <a href="http://example.com">Go to example.com</a>
</div> </div>
<script> <script>
var pElement = document.getElementById("demo"); var pElement = document.getElementById("demo");
pElement.previousElementSibling.style.color = "green"; pElement.nextElementSibling.style.color = "green";
</script> </script>
Internet programming I 40
Child Nodes and Node Values
• The innerHTML property returns the content of an HTML element.

• All the (3) following examples retrieves the text of an <h1> element and copies it into a <p> element:
<h1 id="id01">My First Page</h1>
<p id="id02"> </p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").innerHTML;
</script>
<h1 id="id01">My First Page</h1>
<p id="id02"> </p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").firstChild.nodeValue;
var x=document.getElementById("id01").nodeName; // h1
</script> The nodeName property specifies
the name of a node.
<h1 id="id01">My First Page</h1>
<p id="id02">Hello!</p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").childNodes[0].nodeValue;
</script> Internet programming I 41
Creating Elements (Nodes)
• Before we can insert elements (nodes) to the DOM, we should first know how create them in JavaScript.

• To create an element, use the document.createElement(element) method.


var element = document.createElement(“p”);

• To add text inside the <p> element, we need to create a text node and insert it to the <p> element.

• Use the document.createTextNode(string) to create a text node.

var textNode = document.createTextNode(“ I like JavaScript”);

• Then use the appendChild() method to insert the text node to the <p> element.
element.appendChild(textNode);

• Now, we can insert the created element to another parent element by using again the appendChild() method.

document.getElementById(“demo”).appendChild(element);
42
Web design and programming
Inserting to Elements
• Commonly, we only want to insert to elements not completely replace its content.

• The ParentNode.prepend( ) method inserts an element (node) before the first child of the ParentNode.

• The ParentNode.append( ) method inserts an element (node ) after the last child of the ParentNode.
<ul id=“list”>
<ul id=“list”>
<li>Mangos<li>
<li>Mangos<li>
<li> Bananas<li>
<li> Bananas<li>
<li> Oranges<li>
<li> Oranges<li>
</ul>
</ul>
<button onclick=“fun2( )”> Appen Content </button>
<button onclick=“fun1( )”> Prepend Content </button>
<script>
<script>
var list = document.getElementById(“list”);
var list = document.getElementById(“list”);
function fun2( ) {
function fun1( ) {
var li = document.createElement(“li”);
var li = document.createElement(“li”);
var textNode=document.createTextNode(“Apple”);
var textNode=document.createTextNode(“Apple”);
li.appendChild(textNode);
li.appendChild(textNode);
list.append(li);
list.prepend(li);
}
}
Web design and </script>
Programming 43
</script>
Removing Elements
• To remove an element, use the node.remove( ) method.

• The node.remove( ) method removes the node from the tree it belongs to.

<ul id="list">
<li>Mango</li>
<li>Banana</li>
<li>Apple</li>
</ul>
<button onclick="removeFirstChild()"> Remove First Child </button>
<script>
var list = document.getElementById("list");
function removeFirstChild() {
var firstChild = list.firstElementChild;
firstChild.remove();
}
</script>
Internet programming I 44
Working With Attributes
• With JavaSript and DOM, we can get, set and change an attribute vales.

Getting Attribute Value

• The node.getAttribute(attributeName) returns the value of the specified attribute.

Setting or Changing Attribute Value

• The node.setAttribute(attributeName, value) sets the value of an attribute on the specified element.
<div><img src=“images/star.png” id=“demo”></div>
• If the attribute already exists, the value is changed. <button onclick=“changeSrcAttribue( )”> change </button>
<a href="http://example.com" id="demo">Example.com</a>
<script>
var img = document.getElementById(“demo”);
<script> function changeSrcAttribue( )
var a = document.getElementById("demo"); {
img.setAttribute(“src”,”images/sunflower.png”);
var hrefValue = a.getAttribute("href");
}
alert(hrefVaue); </script>
</script> http://example.com
Web design and programming 45
JS DOM Styling
• With JavaSript and DOM, we can style HTML elements.

Syntax: node.style.property = “value”; //document.getElementById(“demo”).style.color = “red”;


• What about properties with hyphen?
• Properties with hypen like font-size, text-decoration and background-color should be written in camel-case.

Hiding and Showing an Element


• To hide and show an element, set the display property to none and bock respectively.

function hide( ){
document.getElementById(“demo”).style.display=“none”;
}
function show( ){
document.getElementById(“demo”).style.display=“block”;
} 46
JavaScript Events
• JavaScript events are "things" that happen to HTML elements.

• The system fires a signal when events happen, so we can do something when they do.

• When JavaScript is used in HTML pages, JavaScript can "react" on these events.
Common HTML Events
Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page


Internet programming I 47
…cont’d
• For example, we can perform a task when a button is clicked.
var btn = document.getElementById(“btn”);
• The block of code that executes when an event fires is called btn.onclick = function( ){

event handler. It is also called event listener. alert(“The button is clicked”);


}
Inline Event Handlers

• We can also write event handlers inside an HTML element. Using Event handling properties

• This can be done using event handler attributes.

<button onclick=‘alert(“The button is clicked”);’>Click me</button>

• Another example, when the button is clicked the myFunc( ) function will be called.
<button onclick=“myFunc( )”> Click me </button>
function myFunc( ) {
alert(“The button is clicked”);
} Web design and programming 48
The addEventListener( ) Method
• The addEventListener() method sets up a function that will be called when an event happens.

Syntax: element.addEventListener(eventType, listenerFunction);


1. eventType – a string representing the event type

2. listenerFunction – a listener function, it will be called when the event fires.

• Note that you don't use the "on" prefix for the event; use "click" instead of "onclick".
<button id = “btn”>Click me </button>
<script>
var btn = document.getElementById(“btn”);
btn.addEventListener(“click”,function( ) {
alert(“The button is clicked”);
});
Internet programming I 49
</script>
Add Many Event Handlers to the Same Element
• You can add events of different types to the same element:
Example
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);

function myFunction() {
document.getElementById("demo").innerHTML += "Moused over!<br>";
}
function mySecondFunction() {
document.getElementById("demo").innerHTML += "Clicked!<br>";
}
function myThirdFunction() {
document.getElementById("demo").innerHTML += "Moused out!<br>";
}
</script>
Internet programming I 50
Add Many Event Handlers to the Same Element
• The addEventListener() method allows you to add many events to the same element, without overwriting existing
events:
<button id="myBtn">Try it</button>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);
function myFunction() {
alert ("Hello World!");
}
function someOtherFunction() {
alert ("This function was also executed!");
}
</script> Internet programming I 51
More Event Types
The change Event
• The change event fires when the value of the <input>, <select> and <textarea> elements change.
<label> Choose a city<select id =“city” name = “city”>
<option value = “Berlin”>Berlin</option>
<option value = “Tokyo”>Tokyo</option>
<option value = “Rio”>Rio</option>
</select>
</label>
<p> You selected: <span id = “demo”></span></p>
<script>
var select = document.getElementById(“city");
select.addEventListener("change", function(){
document.getElementById(“demo”).innerHTML = select.value;
});
Internet programming I 52
</script>
More Event Types
The keypress Event The mouseover Event
• The keypress event fires when a key is pressed. The mouseover event fires at an element when
a mouse is moved onto the element.
<textarea id ="area"></textarea> <p id="demo">Mouse over to this text …</p>
<p>The value is :<span id="demo"></span></p> <p> Another text here…</p>
<script> <script>
var area = document.getElementById("area"); var elem = document.getElementById("demo");
area.addEventListener("keypress", function(){ elem.addEventListener("mouseover", function(){
document.getElementById("demo").innerHTML = elem.innerHTML = "Hello world";
area.value; elem.style.background="red";

}); });

</script> </script>
Web design and programming 53
More Event Types
The focus Event The blur Event
• The focus event fires when an element is focused. • The blur event fires when an element has lost focus.

<textarea id="area">Type your message…</textarea>


<script>
<textarea id="area">Type your message…</textarea>
var area = document.getElementById(“area");
<script>
area.addEventListener(“focus", function(){
var area = document.getElementById(“area");
area.style.background = “yellow”;
area.addEventListener(“focus", function(){
});
area.style.background = “yellow”; area.addEventListener(“blur", function){
}); area.style.background = “white”;
</script> });
</script>
Web design and programming 54
JavaScript Timing Events
• JavaScript can be executed in time-intervals. This is called timing events.

• The two key methods to use with JavaScript are:

I)setTimeout(function, milliseconds)

Executes a function, after waiting a specified number of milliseconds.


II) setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
• The setTimeout() and setInterval() are both methods of the HTML DOM Window object.
How to Stop the Execution?
• The clearTimeout() method stops the execution of the function specified in setTimeout().
• window.clearTimeout(timeoutVariable)
• The clearInterval() method stops the executions of the function specified in the setInterval()
method.
Web design and programming 55
• window.clearInterval(timerVariable)
JavaScript Timing Events
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
How to display ‘Hello world’ text after 3 seconds How to display a counting time in JavaScript
<body> <body>
<p id="demo"></p>
<h1 id="demo"></h1>
<script>
<script>
setInterval(myTimer, 1000);
function myFunction()
function myTimer()
{
{ document.getElemyentBId("demo").inner const d = new Date();

HTML="Hello world"; document.getElementById("demo").innerHTML =


}
d.toLocaleTimeString();
var myTimeout=setTimeout(myFunction,3000);
</script> }
</script>
5:40:08 AM
</body>
Hello world </body>
</html> Web design and programming 56
</html>
The Browser Object Model (BOM)
• The Browser Object Model (BOM) allows JavaScript to "talk to (interact)” the browser.

• The BOM model is a hierarchy of browser objects that are used to manipulate methods and
properties associated with the web browser itself.

• BOM deals with browser components.

Web design and Programming 57


Form validation
• Form validation is the process of checking that a form has been filled in correctly before it is processed.

• Go to any popular site with a registration form, and you will notice that they provide feedback when you
don't enter your data in the format they are expecting.

• You'll get messages such as:

• "This field is required" (You can't leave this field blank).

• "Please enter your phone number in the format xxx-xxxx" (A specific data format is required for it
to be considered valid).
• "Please enter a valid email address" (the data you entered is not in the right format).

• "Your password needs to be between 8 and 30 characters long and contain one uppercase letter, one
symbol, and a number." (A very specific data format is required for your data).
Web design and programming 58
This is called form validation.
…cont’d

There are two main methods for validating forms:

• server-side (using CGI scripts, ASP, etc), and

• client-side (usually done using JavaScript).

Server-side validation is more secure but often more tricky to code, whereas client-side
(JavaScript) validation is easier to do and quicker too (the browser doesn’t have to
connect to the server to validate the form, so the user finds out instantly if they’ve
missed out that required field!).
Validation done in the browser is called client-side validation, while validation done on
the server is called server-side validation
Web design and programming 59
…cont’d

Client-side form validation Server-side form validation


Web design and programming 60
Different types of client side validation
• There are two different types of client-side validation that you'll encounter on the web:

Built-in form validation uses HTML form validation features, which we've discussed in
chapter two, HTML. This validation generally doesn't require much JavaScript. Built-in form
validation has better performance than JavaScript, but it is not as customizable as JavaScript
validation.

JavaScript validation is coded using JavaScript. This validation is completely customizable,


but you need to create it all (or use a library).
Web design and programming 61
Using built in form validation
 One of the most significant features of modern form controls is the ability to validate most user data

without relying on JavaScript. This is done by using validation attributes on form elements. We've

seen many of these earlier in the HTML, but to recap:

• required: Specifies whether a form field needs to be filled in before the form can be submitted.

• minlength and maxlength: Specifies the minimum and maximum length of textual data (strings).

• min and max: Specifies the minimum and maximum values of numerical input types.

• type: Specifies whether the data needs to be a number, an email address, or some other specific preset

type.

• pattern: Specifies a regular expression that


Webdefines a pattern the entered data needs to follow.
design and programming 62
What is a Regular Expression?
• expression ("regex"): describes a pattern of text
• Regular can test whether a string matches the expr's pattern

• can use a regex to search/replace characters in a string

• very powerful, but tough to read

• A regular expression can be a single character, or a more complicated pattern.

Syntax /w3schools/i is a regular expression.

/pattern/modifiers; w3schools is a pattern (to be used in a search).

• Example /w3schools/ i is a modifier (modifies the search to be case-insensitive).


63
Web design and programming
String regexp methods

64
Web design and programming
Basic regexp
/abc/

• a regular expression literal in JS is written /pattern/

• the simplest regexes simply match a given substring

• the above regex matches any line containing "abc"


• YES : "abc", "abcdef", "defabc", ".=.abc.=."

• NO : "fedcba", "ab c", "AbC", "Bash", ...

Web design and programming 65


Wildcards and anchors

 . (a dot) matches any character except \n


 /.oo.y/ matches "Doocy", "goofy", "LooPy", ...

 use \. to literally match a dot . character

 ^ matches the beginning of a line; $ the end /^the/ matches “the


book”
 /^if$/ matches lines that consist entirely of if /you$/ matches “I love you”
Web design and programming 66
String matches

string.match(regex)
• if string fits pattern, returns matching text; else null
• can be used as a Boolean truthy/falsey test: const regExp = /Hello/gi;
if (name.match(/[a-z]+/)) { ... } const regExpStr = 'oHell world, ohell there!';

• g after regex for array of global matches console.log(regExpStr.match(regExp));

• "obama".match(/.a/g) returns ["ba", "ma"] // Output: null

• i after regex for case-insensitive match // Syntax: RegExp(pattern [, flags])


const regExpConstructor = new RegExp('xyz',
• name.match(/Marty/i) matches "marty", "MaRtY" 'g'); // With flag -g
const str = 'xyz xyz';
console.log(str.match(regExpConstructor));
Using regex constructor:
// Output: ['xyz', 'xyz']
Web design and programming 67
String replace

string.replace(regex, "text")

• replaces first occurrence of pattern with the given text


• var state = "Mississippi";
state.replace(/s/, "x") returns "Mixsissippi"

• g after regex to replace all occurrences


• state.replace(/s/g, "x") returns "Mixxixxippi"

• returns the modified string as its result; must be stored


• state = state.replace(/s/g, "x");
Web design and programming 68
Special characters
| means OR
• /abc|def|g/ matches lines with "abc", "def", or "g"
• precedence: ^Subject|Date: vs. ^(Subject|Date):
• There's no AND & symbol. Why not?

( ) are for grouping


• /(Homer|Marge) Simpson/ matches lines containing
"Homer Simpson" or "Marge Simpson"

\ starts an escape sequence


• many characters must be escaped: / \ $ . [ ] ( ) ^ * + ? var state = ".\nnnnn. abebe";
• "\.\\n" matches lines containing ".\n" var result=state.match(/\.\n/g);
console.log(result);
// '.\n'
Web design and programming 69
Quantifiers: * + ?
* means 0 or more occurrences
• /abc*/ matches "ab", "abc", "abcc", "abccc", ...
• /a(bc)*/" matches "a", "abc", "abcbc", "abcbcbc", ...
• /a.*a/ matches "aa", "aba", "a8qa", "a!?_a", ...

+ means 1 or more occurrences


• /a(bc)+/ matches "abc", "abcbc", "abcbcbc", ...
• /Goo+gle/ matches "Google", "Gooogle", "Goooogle", ...

? means 0 or 1 occurrences
• /Martina?/ matches lines with "Martin" or "Martina"
• /Dan(iel)?/ matches lines with "Dan" or "Daniel“
{min,max} means between min and max occurrences
• /a(bc){2,4}/ matches lines that contain
"abcbc", "abcbcbc", or "abcbcbcbc"

• min or max may be omitted to specify any number


• {2,} 2 or more
• {,6} up to 6
• {3} exactly 3 Web design and programming 70
Character sets

[ ] group characters into a character set;


will match any single character from the set
 /[bcd]art/ matches lines with "bart", "cart", and "dart"
 equivalent to /(b|c|d)art/ but shorter

• inside [], most modifier keys act as normal characters


 /what[.!*?]*/ matches "what", "what.", "what!", "what?**!", ...

– Exercise : Match letter grades e.g. A+, B-, D.

Web design and programming 71


Character ranges
• inside a character set, specify a range of chars with -
 /[a-z]/ matches any lowercase letter
 /[a-zA-Z0-9]/ matches any letter or digit

• an initial ^ inside a character set negates it


 /[^abcd]/ matches any character but a, b, c, or d

• inside a character set, - must be escaped to be matched


 /[\-+]?[0-9]+/ matches optional - or +, followed by at least one digit matches
"-2", “+4", “+777", “-888",
 Exercise : Match phone numbers, e.g. 206-685-2181 .

Web design and programming 72


Built-in character ranges

• \b word boundary (e.g. spaces between words)


• \B non-word boundary var state = "-5 sds +6 sdsd -222 sbsdd +8898";
• \d any digit; equivalent to [0-9] var result=state.match(/\W/g);
console.log(result);
• \D any non-digit; equivalent to [^0-9] // '-', ' ', ' ', '+',
• \s any whitespace character; [ \f\n\r\t\v...] '' ',', ''+'', '-', ' ',
• \S any non-whitespace character
• \w any word character; [A-Za-z0-9_]
• \W any non-word character

 /\w+\s+\w+/ matches two space-separated words

Web design and programming 73


Regex flags

/pattern/g global; match/replace all occurrences


/pattern/i case-insensitive let str = “1st place: Winnie
2nd place: Piglet
/pattern/m multi-line mode 3rd place: Eeyore”;
/pattern/y "sticky" search, starts from a given indexconsole.log( str.match(/^\d/gm) );
// 1, 2, 3
• flags can be combined:
/abc/gi matches all occurrences of abc, AbC, aBc, ABC, ...
var str = "a0bc1";
var str = "a0bc1"; // Indexes: 01234
// Indexes: 01234 var regexp = /\d/y;
var s = str.match(/\d/); regexp.lastIndex =1;
console.log(s); // [‘0’,’1’] var s = str.match(regexp);
console.log(s); // [‘0’]
Web design and programming 74
Using JavaScript form validation
• There are various types of inputs that you can take from a user.

• Text type, email type, password type, radio buttons, and checkboxes are some of the most common
ones that you may encounter.

• Due to these vast majority of input types, you will need to use different logic to validate each of them.

1. Email Validation

<input type="email" placeholder="[email protected]" id="email" required />


HTML

const emailInput = document.getElementById('email');

const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

if (!emailInput.value.match(emailRegex)) Javascript
Web design and programming 75
alert('Invalid email address.');
Using JavaScript form validation
2. Password Validation
<input type="password" placeholder="Enter your password" id="password" required />
<input type="password" placeholder="Enter your password" id="confirm-password" required /> HTML

const password = document.getElementById('password').value;

const confirmPassword = document.getElementById('confirm-password').value;

if (password.value !== confirmPassword.value) {

alert('Entered passwords do not match'); Javascript


}

if (password.length < 6) {

alert('Password must be more than 6 characters long')


Web design and programming 76
}
Using JavaScript form validation
3. Radio Input Validation
<label for="male">Male</label>
<input type="radio" id="male" name="gender" value="male" />
HTML
<label for="female">Female</label>
<input type="radio" id="female" name="gender" value="female" />
<label for="others">Others</label>
<input type="radio" id="others" name="gender" value="others" />
const genders = document.getElementsByName("gender");
const validForm = false;
let i = 0;
while (!validForm && i < genders.length) {
if (genders[i].checked) validForm = true;
JavaScript
i++;
}
if (!validForm) alert("Must check some option!");
Web design and programming 77
Using JavaScript form validation
4. Select Input Validation

<select id="title" required>


<option value="">Select One</option>
<option value="Mr">Mr</option> HTML
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
</select>

const title = document.getElementById('title');


if (title.value = "") { JavaScript
alert('Please select a title');
}
Web design and programming 78
Using JavaScript form validation
5. Checkbox Validation

<input type="checkbox" id="terms"> HTML


<label for="terms">I agree to the terms and conditions</label>

const terms = document.getElementById('terms'); JavaScript


if (!terms.checked) {
alert('Please agree to the terms and conditions to proceed further.');
}
Web design and programming 79
Validate Empty Text Input
<!DOCTYPE html>
<html><head><title> Try It Yourself </title></head>
<body>
<form action=“sample.php" onsubmit="return validateForm()">
<label> First Name: <input type="text" name="firstName"></label>
<input type="submit"> First Name
</form>
<script> submit
function validateForm() {
var firstName = document.getElementsByName("firstName")[0].value;
if(firstName = = "") {
alert("Please enter a value on the text field!");
return false;
}
}
</script>
</body>
Web design and programming 80
</html>
≈//≈

Web design and Programming 81

You might also like