chapter 4(web design and programming)
chapter 4(web design and programming)
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
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.
• 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>
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
• 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
• 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 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
• The HTML DOM is a standard object model and programming interface for HTML. It defines:
The HTML elements as objects
• 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.
• 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";
}
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.
• 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)
• 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.
• 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 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);
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.
• 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.
• 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”;
}
• 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
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 49
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”);
});
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.
• The BOM model is a hierarchy of browser objects that are used to manipulate methods and
properties associated with the web browser itself.
• 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 Size
• Two properties can be used to determine the size of the browser window.
Properties:
• 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.
Some examples:
• The history.back() method loads the previous URL in the history list.
• The history.forward() - method loads the next URL in the history list.
• The cookieEnabled property returns true if cookies are enabled, otherwise false:
• 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.
• 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.
• The window.setInterval(function, milliseconds) method can be written without the window prefix.
• 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
• let x = document.cookie;
• document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
• With JavaScript, you can change a cookie the same way as you create it:
• You don't have to specify a cookie value when you delete a cookie.