0% found this document useful (0 votes)
14K views

Chapter 5 JS

The document outlines a chapter on client-side scripting using JavaScript. It introduces JavaScript basics, including variables, expressions, control structures, arrays, functions, handling events and exceptions, user input forms, cookies and hidden fields. It compares JavaScript to other languages like Java and PHP, explaining key differences like JavaScript being interpreted rather than compiled, its object-oriented nature, and focus on user interfaces. It also covers linking external JavaScript files, using alert statements to display pop-ups, and adding interactivity with buttons.

Uploaded by

Habtamu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14K views

Chapter 5 JS

The document outlines a chapter on client-side scripting using JavaScript. It introduces JavaScript basics, including variables, expressions, control structures, arrays, functions, handling events and exceptions, user input forms, cookies and hidden fields. It compares JavaScript to other languages like Java and PHP, explaining key differences like JavaScript being interpreted rather than compiled, its object-oriented nature, and focus on user interfaces. It also covers linking external JavaScript files, using alert statements to display pop-ups, and adding interactivity with buttons.

Uploaded by

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

27-Jan-20

Wollo University
Outline
Kombolcha Institute of Technology
College of Informatics 2

Department of Information System  Introduction

 Client-Side Scripting Using JavaScript


Introduction to Internet Programming
 Introduction to JavaScript
Chapter 5  JavaScript Basics
Client-Side Scripting Language  Variables ,Expression ,Control Structure
,Array , Functions
(JavaScript)  Handling Events and Exception Handling
 User Inputs : Form Processing
Instructor: Habtamu Abate (M.Sc.)
 Java script Functions
Email: [email protected]
 Cookies and Hidden Fields
1

Client Side Scripting Why use client-side programming?


3 4

PHP already allows us to create dynamic web pages.


Why also use client-side scripting?
 client-side scripting (JavaScript) 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

CS380 CS380

1
27-Jan-20

Why use client-side programming? What is Javascript?


5 6

 server-side programming (PHP) benefits:  a lightweight programming language ("scripting


 security:has access to server's private data; client can't language")
see source code  used to make web pages interactive
 compatibility: not subject to browser compatibility  insert dynamic text into HTML (ex: user name)
issues  react to events (ex: page load user click)
 power: can write files, open connections to servers,
 get information about a user's computer (ex: browser
connect to databases, ... type)
 perform calculations on user's computer (ex: form
validation)

CS380 CS380

What is Javascript? Javascript vs Java


7 8

 a web standard (but not supported identically by  interpreted, not compiled


all browsers)  more relaxed syntax and rules
 NOT related to Java other than by name and some  fewer and "looser" data types
syntactic similarities  variables don't need to be declared

 errors often silent (few exceptions)

 key construct is the function rather than the class


 "first-class" functions are used in many situations
 contained within a web page and integrates with its
HTML/CSS content
CS380 CS380

2
27-Jan-20

Javascript vs Java JavaScript vs. PHP


9 10

 similarities:
 both are interpreted, not compiled
 both are relaxed about syntax, rules, and types

 both are case-sensitive


+ =  both have built-in regular expressions for powerful
text processing

CS380 CS380

Linking to a JavaScript file:


JavaScript vs. PHP script
11 12

 differences: <script src="filename" type="text/javascript"></script>


HTML
 JS is more object-oriented: noun.verb(), less
procedural: verb(noun)  script tag should be placed in HTML page's head
 JS focuses on user interfaces and interacting with a  script code is stored in a separate .js file
document; PHP is geared toward HTML output and  JS code can be placed directly in the HTML file's
file/form processing body or head (like CSS)
 JS code runs on the client's browser; PHP code runs  but this is bad style (should separate content,
on the web server presentation, and behavior

JS <3
CS380 CS380

3
27-Jan-20

Event-driven programming A JavaScript statement: alert


13 14

alert("IE6 detected. Suck-mode enabled.");


JS

 split breaks apart a string into an array using a


delimiter
 can also be used with regular expressions (seen later)
 join merges an array into a single string, placing a  a JS command that pops up a dialog box with a
delimiter between them message
CS380 CS380

Event-driven programming Buttons


15 16

<button>Click me!</button> HTML


 you are used to programs start with a main method
(or implicit main like in PHP)  button's text appears inside tag; can also contain
images
 JavaScript programs instead wait for user actions
called events and respond to them  To make a responsive button or other UI control:
1. choose the control (e.g. button) and event (e.g. mouse
 event-driven programming: writing programs driven
1. click) of interest
by user events
2. write a JavaScript function to run when the event
 Let's write a page with a clickable button that pops occurs
up a "Hello, World" window... 3. attach the function to the event on the control

CS380 CS380

4
27-Jan-20

JavaScript functions Event handlers


17 18

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


statement ; HTML
statement ;
... <button onclick="myFunction();">Click me!</button>
statement ; HTML
} JS
 JavaScript functions can be set as event handlers
function myFunction() {
alert("Hello!");  when you interact with the element, the function will execute
alert("How are you?");
} JS
 onclick is just one of many event HTML attributes we'll
 the above could be the contents of example.js use
linked to our HTML page  but popping up an alert window is disruptive and
annoying
 statements placed into functions can be evaluated in
response to user events  A better user experience would be to have the message
CS380 CS380 appear on the page...

Document Object Model (DOM) DOM element objects


19 20

 most JS code manipulates


elements on an HTML page
 we can examine elements'
state
 e.g. see whether a box is
checked
 we can change state
 e.g. insert some new text into
a div
 we can change styles
 e.g. make a paragraph red

5
27-Jan-20

Accessing elements: Accessing elements:


document.getElementById document.getElementById
21 22

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


JS  document.getElementById returns the DOM object
<button onclick="changeText();">Click me!</button> for an element with a given id
<span id="output">replace me</span>
<input id="textbox" type="text" /> HTML  can change the text inside most elements by setting
function changeText() { the innerHTML property
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");  can change the text in form controls by setting the
textbox.style.color = "red";
value property
} JS

CS380 CS380

Changing element style: Preetify


element.style
23 24

function changeText() {
//grab or initialize text here
Attribute Property or style object
// font styles added by JS:
color color text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
padding padding text.style.color = "red"; // or pink?
} JS
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
CS380 CS380

6
27-Jan-20

Variables Number type


25 26

var name = expression; JS var enrollment = 99;


var medianGrade = 2.8;
var clientName = "Connie Client"; var credits = 5 + 4 + (2 * 3);
var age = 32; JS
var weight = 127.4; JS

 variables are declared with the var keyword (case  integers and real numbers are the same type (no int
sensitive) vs. double)
 types are not specified, but JS does have types  same operators: + - * / % ++ -- = += -= *= /=
("loosely typed") %=
 Number, Boolean, String, Array, Object,  similar precedence to Java
Function, Null, Undefined  many operators auto-convert types: "2" * 3 is 6
 can find out a variable's type by calling typeof
CS380 CS380

Comments (same as Java) Math object


27 28

// single-line comment var rand1to10 = Math.floor(Math.random() * 10 + 1);


/* multi-line comment */ var three = Math.floor(Math.PI);
JS JS

 identical to Java's comment syntax  methods: abs, ceil, cos, floor, log,
max, min, pow, random, round, sin,
 recall: 4 comment syntaxes
sqrt, tan
 HTML: <!-- comment -->
 properties: E, PI
 CSS/JS/PHP: /* comment */

 Java/JS/PHP: // comment
 PHP: # comment

CS380 CS380

7
27-Jan-20

Special values: null and undefined Logical operators


29 30

var ned = null;


var benson = 9;  > < >= <= && || ! == != === !==
// at this point in the code,
// ned is null  most logical operators automatically convert types:
// benson's 9
// caroline is undefined 5 < "7" is true
JS
 42 == 42.0 is true

 undefined : has not been declared, does not  "5.0" == 5 is true

exist  === and !== are strict equality tests; checks both
 null : exists, but was specifically assigned an type and value
empty or null value  "5.0" === 5 is false
 Why does JavaScript have both of these?
CS380 CS380

if/else statement (same as Java) Boolean type


31 32

if (condition) { var iLike190M = true;


statements; var ieIsGood = "IE6" > 0; // false
} else if (condition) { if ("web devevelopment is great") { /* true */ }
statements; if (0) { /* false */ }
} else { JS
statements;
}  any value can be used as a Boolean
JS
 "falsey" values: 0, 0.0, NaN, "", null, and undefined
 identical structure to Java's if/else statement
 "truthy" values: anything else
 JavaScript allows almost anything as a condition
 converting a value into a Boolean explicitly:
 var boolValue = Boolean(otherValue);
 var boolValue = !!(otherValue);

CS380 CS380

8
27-Jan-20

for loop (same as Java) while loops (same as Java)


33 34

var sum = 0; while (condition) {


for (var i = 0; i < 100; i++) { statements;
sum = sum + i; } JS
} JS

var s1 = "hello"; do {
var s2 = ""; statements;
for (var i = 0; i < s.length; i++) { } while (condition);
s2 += s1.charAt(i) + s1.charAt(i); JS
}
// s2 stores "hheelllloo" JS  break and continue keywords also behave as in
Java

CS380 CS380

Popup boxes Arrays


35 36

alert("message"); // message var name = []; // empty array


confirm("message"); // returns true or false var name = [value, value, ..., value]; // pre-filled
prompt("message"); // returns user input string name[index] = value; // store element
JS JS

var ducks = ["Huey", "Dewey", "Louie"];


var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS

CS380 CS380

9
27-Jan-20

Array methods String type


37 38

var a = ["Stef", "Jason"]; // Stef, Jason var s = "Connie Client";


a.push("Brian"); // Stef, Jason, Brian var fName = s.substring(0, s.indexOf(" ")); // "Connie"
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian var len = s.length; // 13
a.pop(); // Kelly, Stef, Jason var s2 = 'Melvin Merchant';
a.shift(); // Stef, Jason JS
a.sort(); // Jason, Stef
JS  methods: charAt, charCodeAt, fromCharCode,
 array serves as many data structures: list, queue, indexOf, lastIndexOf, replace, split,
stack, ... substring, toLowerCase, toUpperCase
 methods: concat, join, pop, push, reverse, shift,  charAt returns a one-letter String (there is no char type)
slice, sort, splice, toString, unshift  length property (not a method as in Java)
 push and pop add / remove from back
 Strings can be specified with "" or ''
 unshift and shift add / remove from front

 shift and pop return the element that is removed


 concatenation with + :
1 + 1 is 2, but "1" + 1 is "11"

More about String Splitting strings: split and join


39 40

 escape sequences behave as in Java: \' \" \& \n \t var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown", "fox"]
\\ a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
 converting between numbers and Strings: JS
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah  split breaks apart a string into an array using a
ah ah!"
var n1 = parseInt("42 is the answer"); // 42 delimiter
var n2 = parseFloat("booyah"); // NaN JS
 can also be used with regular expressions (seen later)
 accessing the letters of a String:  join merges an array into a single string, placing a
var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
delimiter between them
var lastLetter = s.charAt(s.length - 1); JS
CS380

10
27-Jan-20

41 The End !!!


Question???

CS380

11

You might also like