chapter Four(web programming)
chapter Four(web programming)
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?
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
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
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
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
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
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
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
Web Programming 35
Common event HTML attributes
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”);
• 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.
• 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
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