0% found this document useful (0 votes)
3 views50 pages

chapter Four(web programming)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views50 pages

chapter Four(web programming)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 50

ARBA MINCH UNIVERSITY

Web
Programming
FCSE / Computer Science

Instructors:
• Chala Simon

Web Programming 1
<q> Talk is cheap. Show me the code.</q> …...... Linus Torvalds (Founder of Linux kernel)
Chapter Four Client-side programming –Javascript (JS)

Web Programming 2
Contents
• Introduction
• Language Format
• Variables
• Functions in JavaScript
• DOM
• Event handlers
• Form validation

Web Programming 3
Client-side vs server-side scripting

Web Programming 4
Why use client-side programming?
• client-side scripting benefits:
• usability: can modify a page without having to post back to the
server (faster UI)
• efficiency: can make small, quick changes to page without waiting
for server
• event-driven: can respond to user actions like clicks and key
presses

Web Programming 5
What is JavaScript?
• a lightweight programming language ("scripting language")
• used to make web pages interactive
• insert text into HTML
• document.getElementById("demo").innerHTML = "Hello JavaScript";
• Can Change HTML Attribute Values
• <button onclick="document.getElementById('myImage').src=‘dog.gif'"> Change</button>
• Can change HTML Styles (CSS)
• document.getElementById("demo").style.fontSize = "35px";
• react to events (ex: page load user click) onclick="alert("reload page")"
• get information about a user's computer (ex: browser type) window.navigator.userAgent
• 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 Programming 6
Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

• HTML to define the content of web pages

• CSS to specify the layout of web pages

• JavaScript to program the behavior of web pages

Web Programming 7
Language Format
• JavaScript has the following format
<script>

//javascript code goes here

</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 javaScript file
<script src=“filename.js”> </script>

• External scripts are practical when the same code is used in many different
web pages
Web Programming 8
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>


and maintain <p id="demo">A Paragraph.</p>
• Cached JavaScript files can speed up page loads <button type="button" onclick="myFunction()">Try
it</button>
 To add several script files to one page
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
 Example
<script src="myScript.js"></script>
• <script src="myScript1.js"></script>
</body>
• <script src="myScript2.js"></script> </html>
Web Programming 9
Displaying messages
• document.write(message)
• Displays message in html window
• will delete all existing HTML
• alert(message)
• Displays message on pop up window as info
• Sometimes annoying
• 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
• Console.log(message)
• Displays message in the browsers console- not visible on the web page.

Web Programming 10
Variables
• variables are declared with the var or let keyword (case sensitive)
• types are not specified, but JS does have types ("loosely typed")
• Number, Boolean, String, Array, Object, Function,
Null, Undefined
• can find out a variable's type by calling typeof

var name = expression; JS

var clientName = "Connie Client";


var age = 32;
var weight = 127.4; JS

Web Programming 11
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:
• let x1 = 34.00; // Written with decimals /*
let x2 = 34; // Written without decimals Multiple line
comment
Web Programming 12
*/
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;
• (x == y) // Returns true console.log(typeof age); // number
• 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 Programming 13
JavaScript Data Types
JavaScript array
• 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
• cars.sort() // Sorts the array
Web Programming 14
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 ().
• JavaScript uses the function keyword to declare a function
function name() {
statement ;
statement ;
...
statement ;
} JS

• statements placed into functions can be evaluated in response to user events


15

• 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)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
function myFunction(p1, p2) {
return p1 * p2; // The function returns the
product of p1 and p2
document.getElementById("demo").innerHTML = myFunction(4, 3); }
Web Programming 16
JavaScript Functions
There are 3 ways of writing a function in JavaScript:

1- Function Declaration: 2. Function Expression:


• Function Expression is another way to define a
• Function Declaration is the traditional way to
define a function. function in JavaScript. Here we define a function
using a variable and store the returned value in
• It is somehow similar to the way we define a
function in other programming languages. that variable.
// Function declaration / /Function Expression
function add(a, b) { const add = function(a, b) {
console.log(a + b); console.log(a+b);
} }
// Calling a function // Calling function
add(2, 3); // 5 add(2, 3); // 5

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

console.log(great(3,5)); // b is greater
Web Programming 18
Document Object Model (DOM)
• When a web page is loaded, the browser creates a Document Object Model of the page.
• Treats all HTML elements as objects
• It is a w3c standard for how to :
• Get
• Change
• Add or
• Delete HTML elements
• 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

• Therefore, The DOM is a ‘tree structure’ representation of an HTML structure.


Web Programming 19
Document

<!DOC TYPE html> Root element


<HTML>
<html>
<head>
<title>My title</title>
</head> Element <head> Element <body>
<body>
<a href=“m.html”>My link</a>
<p> my paragraph</p> Element :<a> Element:<p>
Element <title>
</body>
</html> Attribute:”href”
Text:
"my paragraph”

Text: “My title” Text: "My link”


Web Programming 20
DOM element objects

Web Programming 21
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>
Select the Topmost Elements <script>
• The topmost elements can be selected directly from alert(document.documentElement.getAttribute("lang"));
alert(document.body.firstElementChild.innerHTML);
the document object properties.
document.body.style.backgroundColor ="green";
• document.documentElement selects <html> </script>
• document.head. Selects <head> </body>
• document.body. Selects <body> </html>
Web design and Programming 22
Accessing elements
• Use the following methods to access elements:
• document.getElementById(id)
• document.getElementsByTagName(name)
• document.getElementsByClassName(name)
• document.getElementsByName(name)

Web Programming 23
Accessing elements: document.getElementById

 document.getElementById returns the


DOM object for an element with a
given id <p id="demo"></p>

 It is the best method to use when


<script>
selecting a single element. Var element =
document.getElementById(“demo"
 The easiest way to find an HTML );
element.innerHTML = “hello
element in the DOM, is by using the
world”;
element id. </script>

Web Programming 24
Accessing elements: document.getElementById

var name = document.getElementById("id");


JS

<button onclick="changeText();">Click me!</button>


<input id="textbox" type="text" />
<span id="output">replace me</span>
HTML

function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
span.innerHTML=textbox.value
textBox.style.color = "red";

} JS

Web Programming 25
Accessing elements: document.getElementsByClassName
• 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 26
Accessing elements: document.getElementsByTagName
• 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> Web design and Programming 27
Accessing elements: document.getElementsByName
• 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; First Name:
var lastName = document.getElementsByName("lastName")[0].value;
var fullName = "Your full name is " + firstName +" " +lastName; Last Name:
alert(fullName);
} Get Values
</script> Web design and Programming 28
Select Elements Using CSS Selectors
• The document.querySelectorAll() selects all elements that match the specified selector.
• The selector must be a valid CSS selector. Selects the first match element
• It returns an array of the selected elements(nodes).
•<pIn this example, ipsum</p>
id="demo">Lorem the element with the demo id is selected.
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> Hello World!
var x = document.querySelectorAll(".red-color");
Hello World!
for (let i = 0; i < x.length; i++) {
x[i].style.color = "red"; Hello World!
x[i].style.fontSize ="20px";
} Web design and Programming 29
</script>
DOM object properties
<div id="main" class="foo bar">
<p>Hello, I am <em>very</em> happy to see you!</p>
<img id="icon" src="images/potter.jpg" alt=“Potter" />
</div> HTML

Property Description Example


tagName element's HTML tag $("main").tagName is "DIV"
className CSS classes of element $("main").className is "foo bar"
$("main").innerHTML is "\n
innerHTML content inside element
<p>Hello, <em>ve...
$("icon").src is
src URL target of an image
"images/potter.jpg"
Web Programming 30
DOM properties for form controls
<input id="sid" type="text" size="7" maxlength="7" />
<input id="frosh" type="checkbox" checked="checked" /> Freshman?
HTML

Property Description Example


$("sid").value could be
value the text in an input control
"1234567"
checked whether a box is checked $("frosh").checked is true
whether a control is disabled
disabled $("frosh").disabled is false
(boolean)
readOnly whether a text box is read-only $("sid").readOnly is false

Web Programming 31
Changing element style: element.style

CSS property Property in JS/style

color color

padding padding

background-color backgroundColor

border-top-width borderTopWidth

Font size fontSize

Font famiy fontFamily

Web Programming 32
Example

function changeText() {
//grab or initialize text here

// font styles added by JS:


text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
} JS

Web Programming 33
JavaScript Events
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can "react" on
these events.
• Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
• Often, when events happen, you may want to do something.
• JavaScript lets you execute code when events are detected.
• HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.

Web Programming 34
Event handlers
• JavaScript functions can be set as event handlers
• when you interact with the element, the function will execute

<element attributes onclick="function();">...


HTML

<button onclick="myFunction();">Click me!</button>


HTML

• onclick is just one of many event HTML attributes we'll use


• but popping up an alert window is disruptive and annoying
• A better user experience would be to have the message appear on the page...

Web Programming 35
Common event HTML attributes

• onsubmit - called when submit button is clicked


• onclick - called when a button is clicked
• onreset - called when the reset button is clicked
• onload - called after a webpage loads
• onmouseover - called when mouse pointer enters element area
• onmouseout - called when mouse pointer leaves element area
• onfocus - called when control receives focus
• onblur - called when a control loses focus
• onchange - called when a control loses focus and the value of its contents has
changed

Web Programming 36
…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 37
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”);
});
</script>
Web design and Programming 38
Add Multiple Event Handlers to the Same Element
<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> • You can add events of different types to the same element:
Web design and Programming 39
Form data Validation

Web Programming 40
What is form validation?
• validation: ensuring that form's values are correct
• some types of validation:
• preventing blank values (email address)
• ensuring the type of values
• integer, real number, currency, phone number, Social Security number, postal
• address, email address, date, credit card number, ...
• ensuring the format and range of values (ZIP code must be a 5-digit integer)
• ensuring that values fit together (user types email twice, and the two must
match)
• Requires knowledge of regular expressions – a pattern matching
technique.

Web Programming 41
JavaScriptRegularExpressionMatchingMetacharacters

Web Programming 42
JavaScript Regular Expression Counting Metacharacters

Web Programming 43
JavaScript Regular Expression Positional Metacharacters

Web Programming 44
JavaScript Regular Expression methods for matching pattern

• The RegExp() object is used for matching text with a pattern.


• Two methods are available
• regexObject.test(string)
• string.search(regexObject)
• The first is a regular expression object method, the second a string
object method. Both perform the same task and influence the same
related objects, but they return different values:
• a Boolean value for test() and
• a character offset value for search() [ or -1 if no match is found ].
• Which method you choose depends on whether you need only a
true/false verdict on a match or the location within the main string of
the start of the substring.

Web Programming 45
Example- Use of search method

Web Programming 46
The view in browser

Web Programming 47
Exercise 1– create the following menu with js

Web Programming 48
Exercise 2 – Grade report

Web Programming 49
The End

Web Programming 50

You might also like