Chapter 4
Chapter 4
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
CSS JavaScript
( Style ) ( Behavior )
• <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>
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").style.fontSize = "35px";
document.getElementById("demo").style.display = "none";
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:
• 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
• prompt(message)
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
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.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:
• This code assigns many values (John, Doe, 50,blue) to a variable named person:
• 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,
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)
• The HTML DOM is a standard object model and programming interface for HTML. It defines:
The HTML elements as objects
console.dir(icon);
• 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.
• In this example, we use the document.getElementsByName to select inputs by their name attributes.
• 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.
• 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)
• 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.
• 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 add text inside the <p> element, we need to create a text node and insert it to the <p> element.
• 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.
• 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.
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
onmouseout The user moves the mouse away from an HTML element
• We can also write event handlers inside an HTML element. Using Event handling properties
• 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.
• 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.
I)setTimeout(function, milliseconds)
• The BOM model is a hierarchy of browser objects that are used to manipulate methods and
properties associated with the web browser itself.
• 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.
• "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
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
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.
without relying on JavaScript. This is done by using validation attributes on form elements. We've
• 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.
64
Web design and programming
Basic regexp
/abc/
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!';
string.replace(regex, "text")
? 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"
• 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
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
if (password.length < 6) {