Chapter Four(Web Programming)
Chapter Four(Web Programming)
Web
Programming
FCSE / Computer Science
Instructors:
• Behailu Mitiku.
• 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)
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)
• 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 Programming 6
Why Study JavaScript?
Web Programming 7
Language Format
• JavaScript has the following format
<script>
</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
• Cached JavaScript files can speed up page loads <button type="button" onclick="myFunction()">Try
it</button>
To add several script files to one page use several script tags
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
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:
JavaScript comments
• let answer = "It's alright";
JavaScript Numbers // single line comment
• JavaScript has only one type of numbers.
• Numbers can be written with, or without decimals: /*
• let x1 = 34.00; // Written with decimals Multiple line
let x2 = 34; // Written without decimals
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;
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 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
15
• statements placed into functions can be evaluated in response to user events
…
• 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:
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.
It is used to shorten the code. ‘Here we do not • Also, when there are multiple lines of code in the
use the “function” keyword and use the arrow bracket we should write return explicitly to return the
symbol.
// Single line of code value from the function.
Web Programming
console.log(great(3,5)); // b is greater 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
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>
</head>
To get or change their attribute
<body>
To remove them <h1>My Header</h1>
And many more… <p> My Paragraph</p>
<script>
Select the Topmost Elements alert(document.documentElement.getAttribute("lang"));
• The topmost elements can be selected directly from alert(document.body.firstElementChild.innerHTML);
the document object properties. document.body.style.backgroundColor ="green";
</script>
• document.documentElement selects <html>
</body>
• document.head. Selects <head> </html>
Web design and Programming 22
• document.body. Selects <body>
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
Web Programming 24
Accessing elements: document.getElementById
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.
• 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> 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
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Web Programming 32
Example
function changeText() {
//grab or initialize text here
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
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
• 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”);
}
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”);
});
</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>";
}
• You
Web designcan add events
and Programming of different types to the same element: 39
</script>
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
JavaScript Regular Expression Matching Metacharacters
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
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