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

chapter 4(web design and programming)

Chapter Four discusses client-side programming using JavaScript, highlighting its role in making web pages interactive and dynamic. It covers fundamental concepts such as variables, functions, event handlers, and the Document Object Model (DOM), along with practical examples of JavaScript code. The chapter emphasizes the importance of JavaScript in web development alongside HTML and CSS.

Uploaded by

firaolfro
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)
3 views

chapter 4(web design and programming)

Chapter Four discusses client-side programming using JavaScript, highlighting its role in making web pages interactive and dynamic. It covers fundamental concepts such as variables, functions, event handlers, and the Document Object Model (DOM), along with practical examples of JavaScript code. The chapter emphasizes the importance of JavaScript in web development alongside HTML and CSS.

Uploaded by

firaolfro
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/ 65

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
• Event handlers
• DOM
• 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.

• But code separation is advised (content – presentation – behavior )

• Use the following tag in – html to link external

• 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>
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


Web design and Programming 7
document.getElementById("demo").style.display = "block";
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


Web element is a common way to display data in HTML.
design and Programming 8
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:
Web design and Programming 9
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
• let x1 = 34.00; // Written with decimals comment
Web design and Programming */ 13
let x2 = 34; // Written without decimals
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
(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>
37
Math.floor(Math.random() * 10); <h2>JavaScript Math</h2>
<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);
Web design and Programming 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);
// 5
Web design and Programming 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
}
Web design and Programming 22
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 Classes <!DOCTYPE html>
<html>
• JavaScript Classes are templates for JavaScript Objects. <body>
Syntax <p id="demo"></p>
<script>
class ClassName { class Car {
constructor() { ... } constructor(name, year) {
} this.name = name;
this.year = year;
Example
}
class Car { age(x) { My car is 8 years old.
constructor(name, year) { return x - this.year;
this.name = name; }
}
this.year = year; let date = new Date();
} let year = date.getFullYear();
} let myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML=
Using a Class "My car is " + myCar.age(year) + " years old.";
• When you have a class, you can use the class to create objects: </script>
Example </body>
</html>
let myCar1 = new Car("Ford", 2014); Web design and Programming 25
let myCar2 = new Car("Audi", 2019);
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
getTime() Get the time (milliseconds since January 1, 1970)
d.getMilliseconds(); //639

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


Date.now() Get the time. ECMAScript 5.Web design and Programming 26
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


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

Web design and Programming 28


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

Web design and Programming 29


JavaScript DOM Selectors
• With JavaScript, we can select any element from the DOM tree using the document object.
Why do we select elements?
 To get their content <!DOC TYPE html>
 To change their content <html lang=“en”>
<head>
 To style them <title>The Text </title>
 To get or change their attribute </head>
 To remove them <body>
<h1>My Header</h1>
 And many more… <p> My Paragraph</p>
Select the Topmost Elements <script>
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";
• document.documentElement selects <html> </script>
</body>
• document.head. Selects <head>
</html>
• document.body. Selects <body>
Web design and Programming 30
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 = document.getElementById(“demo");
element.innerHTML = “hello world”;
</script> Web design and Programming 31
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>
Web design and Programming 32
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";
}
Web design and Programming 33
</script>
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
Web design and Programming 34
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";
}
Web design and Programming 35
</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
Web design and Programming 36
• Siblings (brothers or sisters) are nodes with the same parent
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 theWeblast child of <html>
</html> design and Programming
 Hello world! Is a child of <p>
37
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>
<script>
var pElement = document.getElementById("demo")
pElement.parentElement.style.background = "gold";
</script> Web design and Programming 38
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) Web design and Programming (b) 39
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> Web design and Programming 40
Navigating Element Nodes
• The previousElementsSibling property returns the previous element prior to the specified one in a parent’s
children list.

• The nextElementsSibling 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>
Web design and Programming 41
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> Web design and Programming 42
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);
Web design and Programming 43
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 44
</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>
Web design and Programming 45
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 46
JS DOM Styling
• With JavaSript and DOM, we can style HTML elements.

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

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”;
}

• What about properties with hyphen?

• Properties with hypen like font-size, text=decoration and background-color should be written in camel-case.
• font-size = fontSize • text-decoration = textDecoration • background-color = backgroundColor
Web design and Programming 47
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


Web design and Programming 48
…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 49
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”);
});
Web design and Programming 50
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>
Web design and Programming 51
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> Web design and Programming 52
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;
});
Web design and Programming 53
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(){
var val = document.getElementById("area").value;
elem.innerHTML = "Hello world";
document.getElementById("demo").innerHTML =
elem.style.background="red";
area.value;
});
});
</script>
</script> Web design and Programming 54
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 55
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 56


The Window Object
• The window represents the current browser window.

• All global JavaScript objects, functions, and variables automatically become members of the window object.

• Even the document object (of the HTML DOM) is a property of the window object:

• window.document.getElementById("header"); is the same as: document.getElementById("header");

Window Size
• Two properties can be used to determine the size of the browser window.

• Both properties return the sizes in pixels:


Some other Window methods:
window.innerWidth - the inner width of the browser window (in pixels)
• window.open() - open a new window
window.innerHeight - the inner height of the browser window (in pixels) • window.close() - close the current window

Web design and Programming 57


JavaScript Window Screen
• The window.screen object contains information about the user's screen.

• The window.screen object can be written without the window prefix.

Properties:

• screen.width;-returns the width of the visitor's screen in pixels.

• screen.height:-returns the height of the visitor's screen in pixels.

• screen.availWidth:-returns the width of the visitor's screen, in pixels, minus interface features like the

Windows Taskbar.

• screen.availHeight;-returns the height of the visitor's screen, in pixels, minus interface features like the

Windows Taskbar.

• screen.colorDepth;-returns the number of bits used to display one color.


Web design and Programming 58
• screen.pixelDepth;-returns the pixel depth of the screen.
JavaScript Window Location
• The window.location object can be used to get the current page address (URL) and to redirect the

browser to a new page.

• The window.location object can be written without the window prefix.

Some examples:

• window.location.href returns the href (URL) of the current page

• window.location.hostname returns the domain name of the web host

• window.location.pathname returns the path and filename of the current page

• window.location.protocol returns the web protocol used (http: or https:)


Web design and Programming 59
• window.location.port() returns the port number used
JavaScript Window History
• The window.history object contains the browsers history.

• The window.history object can be written without the window prefix.

• The history.back() method loads the previous URL in the history list.

This is the same as clicking the Back button in the browser.

• The history.forward() - method loads the next URL in the history list.

This is the same as clicking the Forward button in the browser.


<script>
<script> function goForward() {
function goBack() { window.history.forward()
window.history.back() }
} </script>
</script> </head>
</head> <body>
<body> <input type="button" value="Forward" onclick="goForward()"
<input type="button" value="Back" onclick="goBack()"> >
Web design and Programming 60
JavaScript Window Navigator
• The window.navigator object contains information about the visitor's browser.

• The appName property returns the application name of the browser:

• The cookieEnabled property returns true if cookies are enabled, otherwise false:

• The appVersion property returns version information about the browser:

• The platform property returns the browser platform (operating system):

• The language property returns the browser's language:

• The onLine property returns true if the browser is online:

• The javaEnabled() method returns true if Java is enabled:

Web design and Programming 61


JavaScript Popup Boxes
• JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

• An alert box 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("some text");

• A confirm box 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("some text");


• A prompt box 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.62
Web design and Programming
JavaScript Timing Events
• The setInterval( ) method repeats a given function at every given time-interval.

• The window.setInterval(function, milliseconds) method can be written without the window prefix.

• The first parameter is the function to be executed.

• The second parameter indicates the length of the time-interval between each execution.

• The clearInterval() method stops the executions of the function specified in the setInterval() method.

• This example executes a function called "myTimer" once every second (like a digital watch).
setInterval(myTimer, 1000);
function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML =
d.toLocaleTimeString();
Web design and Programming 63
}
JavaScript Cookies
What are Cookies?
• Cookies are data, stored in small text files, on your computer.
• When a web server has sent a web page to a browser, the connection is shut down, and the server
forgets everything about the user.
• Cookies were invented to solve the problem "how to remember information about the user":
• When a user visits a web page, his/her name can be stored in a cookie.
• Next time the user visits the page, the cookie "remembers" his/her name.
• Cookies are saved in name-value pairs like: username = John Doe
Create a Cookie with JavaScript
• JavaScript can create, read, and delete cookies with the document.cookie property.
• With JavaScript, a cookie can be created like this:
• document.cookie = "username=John Doe";
• You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is
closed:
• document.cookie = "username=John Doe; Web expires=Thu, 18 Dec 2013 12:00:00 UTC";
design and Programming 64
JavaScript Cookies
Read a Cookie with JavaScript

• With JavaScript, cookies can be read like this:

• let x = document.cookie;

• document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

Change a Cookie with JavaScript

• With JavaScript, you can change a cookie the same way as you create it:

• document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

• The old cookie is overwritten.

Delete a Cookie with JavaScript

• You don't have to specify a cookie value when you delete a cookie.

• Just set the expires parameter to a past date:


Web design and Programming 65

You might also like