The Internet 12/8/11 JavaScript Review

Slides:



Advertisements
Similar presentations
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
Advertisements

Information Technology Center Hany Abdelwahab Computer Specialist.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
JavaScript Part 1.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing.
Integrating JavaScript and HTML5 HTML5 & CSS 7 th Edition.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
TUTORIAL 10: PROGRAMMING WITH JAVASCRIPT Session 2: What is JavaScript?
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
05 – Java Script (1) Informatics Department Parahyangan Catholic University.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
Java Script About Java Script Document Object Model Incorporating JavaScript Adding JavaScript to HTML Embedding a Javascript External Scripts Javascript.
CIS 3.5 Lecture 2.3 "Introduction to JavaScript".
JavaScript Event Handlers. Introduction An event handler executes a segment of a code based on certain events occurring within the application, such as.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
CIS 228 The Internet 11/17/11 Of Timers and Cookies.
CIS 228 The Internet Day 28, 12/13 Review. Alphabet Soup HTML (delineates document structure) HyperText Markup Language CSS (specifies document presentation)
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
CIS 228 The Internet 12/6/11 Forms and Validation.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
Introduction to JavaScript MIS 3502, Fall 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 9/29/2016.
Build in Objects In JavaScript, almost "everything" is an object.
Java Script Introduction. Java Script Introduction.
JavaScript and HTML Simple Event Handling 11-May-18.
Week 3: Introduction to Javascript
Chapter 6 JavaScript: Introduction to Scripting
Web Development & Design Foundations with HTML5
JavaScript is a programming language designed for Web pages.
In this session, you will learn about:
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
Web Development & Design Foundations with HTML5 7th Edition
Introduction to Scripting
JavaScript for Beginners
14 A Brief Look at JavaScript and jQuery.
JavaScript and HTML Simple Event Handling 19-Sep-18.
Objectives Insert a script element Write JavaScript comments
DHTML Javascript Internet Technology.
Your 1st Programming Assignment
CSS Colors, JavaScript Variables, Conditionals and Basic Methods
WEB PROGRAMMING JavaScript.
Integrating JavaScript and HTML
Events Comp 205 Fall 2017.
DHTML Javascript Internet Technology.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
JavaScript Defined General Syntax Body vs. Head Variables Math & Logic
The Internet 11/29/11 Functions
Functions, Regular expressions and Events
The Internet 11/15/11 Handling Data in JavaScript
The Internet 11/22/11 Conditionals and Loops
Tutorial 10: Programming with javascript
JavaScript Basics What is JavaScript?
JavaScript: Introduction to Scripting
JavaScript Intro.
PHP an introduction.
JavaScript and Ajax (JavaScript Events)
Web Programming and Design
Programming Basics Review
JavaScript for Beginners
Web Programming and Design
Web Programming and Design
JavaScript and HTML Simple Event Handling 26-Aug-19.
JavaScript and HTML Simple Event Handling 4-Oct-19.
Presentation transcript:

The Internet 12/8/11 JavaScript Review CIS 228 The Internet 12/8/11 JavaScript Review

Attaching JavaScript to XHTML Event attributes of elements (in <body>) Calls to JavaScript functions Example attribute: onload=“action” <body onload=”initialize()”> <script> element (in <head>) Attribute: type=“text/javascript” Attribute: src=“cookie.js” (JavaScript in a file) Definitions of JavaScript functions <script type=”text/javascript”> function initialize() { … } </script>

Event Attributes onload when the page loads (in opening body tag) <body onload=“initialize()”> onclick when the mouse clicks on an element <input type=“button” onclick=“validate(this)” /> onfocus when the focus is on an element <input type=“text” onfocus=“setDefault(this)” /> onblur when the focus leave an element <input type=“text” onblur=“notEmpty(this)” /> onchange when focus leaves and the value changes <input type=“text” onchange=“refigure(this)” />

Timers One-time timers Repeating timers Canceling repeating timers setTimeout(what, when); what – action to take (e.g., “alert('wake up!');”) when – time delay in milliseconds (e.g., 5 * 60 * 1000) Repeating timers const timerId = setInterval(what, when); what – action to take when – time between repeated actions Canceling repeating timers clearInterval(timerId);

JavaScript Functions Built in functions Example User defined functions Reusable chunks of code that accomplish common tasks Built in functions alert('hello world'); Displays text in a pop up window prompt('first message', 'second message'); Solicits data from user Example <body onload=“alert('hello world');”> User defined functions Bundle together small tasks into bigger ones

User-Defined Functions Declaration: function name (param * ,) block function fib (n) { if (n<=1) return 1; return fib(n-2) + fib(n-1); } Call (expression or statement): name (args * ,) var x = fib(17)/3; complainToUser(x, “ is not a number!”); Return statement: return expression? ; return;

Comments XHTML comments CSS comments JavaScript comments <!--This is an HTML comment--> CSS comments /* This is a CSS comment */ JavaScript comments // text to the end of line ignored /* Multi-line comment */ Temporary comments are useful for debugging

JavaScript Identifiers Identifiers name functions and locations Rules: 1 or more characters First character must be: letter or “_” or “$” All characters must be: letter or digit or “_” or “$” Spaces and other special characters are not allowed Camel case convention (for variables) thisIsACamelCaseVariableId Upper case convention (for constants) THIS_IS_AN_UPPER_CASE_CONSTANT_ID

JavaScript Data Types String (text) (e.g. “this is a string”, 'so is this', 'don\'t worry') Number Integer (e.g., 23, 0, -37) Decimal (e.g., 3.1415, -0.003826, 5498621.0) Boolean true or false Object (e.g., arrays, regular expressions, elements, document)

The document Object Can appear on either side of an assignment document (the root of the “DOM” object) .getElementById(“x”) (the element with id=“x”) .sytle (the style attribute of that element) .height (the height of the element) .color (the color of the element) .getElementById(“i”) (and the element is img) .src (the URL of the file containing an image) .getElementById(“f”)(and the element is a form field) .value (the value entered in the field)

JavaScript Variables Associate a name with a value Variable – the value may change Declaration: var s = “The user name is ”; Declarations should usually initialize their variables Use: var userName = prompt(s+“?”, ””); Definition: s = s + userName; Values have types; locations do not! var x = 17; (x is a number) x = “” + x; (x is a string) Arrays are objects (values) that contain variables

Arrays A collection of variables with the same name differentiated by an index (key) Declaration: var a = new array(5); // size, 5, optional var b = [“red”, “yellow”, “blue”]; Use: var c = “color: ” + b[2]; a[2] = (a[1] + a[3]) / 2; Size: a.length

Associative Arrays Array - collection of variables with the same name differentiated by an index (key) Keys can be Strings as well as integers. var atomicNumber = new Array(); atomicNumber[“hydrogen”] = 1; atomicNumber[“carbon”] = 6; atomicNumber[“oxygen”] = 8; Var ratio = 64 / atomicNumber[“zinc”]; Form element maps field names to the fields myForm[“zipcode”] = “10468”;

Cookies Medium-term persistent storage for small values List of name-value pairs (total size is browser dependent) Name is an identifier Value is a String Expiration date Helper functions (cookie.js) writeCookie(name, value, days); readCookie(name); eraseCookie(name); Not all browsers support cookies Navigator.cookiesEnabled

JavaScript Expressions String operator: + (concatination) e.g., s + userName, “Bowen” + “ ” + “Alpern” Numeric operators: +, -, *, /, % e.g., 3+4, 3-4, 3*4, 3/4, 3%4, 3.14*r*r/2 Comparison operators: ==, !=, <, <=, >, >= e.g., 3+4 != 8, 4/2 == 2, userName == “malcolmX” Boolean operators: !, &&, || e.g., !done && ((3*x+7<21 || 5>2*x || x==0)) e.g., s==“done” || !(name!=“Bowen” && s==“first”)

JavaScript Conversions Error values: undefined – uninitialized locations (always initialize) NaN – not a number (e.g., 'sam' / 3 == NaN) Automatic conversions “12” / “6” == “12” / 6 == 12 / “6” == 12 / 6 == 2 “6” + “3” == “6” + 3 == 6 + “3” == “63” == 63 != 6 + 3 2 + 3.14 == 3.14 + 2 == 3.14 + 2.0 = 5.14 Explicit conversions ParseInt(“6”) + parseInt(“3”) == 6 + 3 == 9 ParseFloat(“3.14”) + 2 == 5.14

Assignments Form: variable = expression ; Examples: i = i+1; s = “hello world!”; b = isPrime(p) && (q < p || isPrime(q)); x = 3.1415 * gcd(15, 33); a[i] = “seat ” + i; var j = i*(i-1)/2; var v = document.getElementById(s).value; document.getElementById(s).value = 99*v;

innerHTML Property A property of XHTML elements <script type= “text/javascript”> function enterText(el) { Var in = prompt(“enter text”, “”); el.innerHTML = in; } </script> ... <h2>Enter your HTML text</h2> <p onclick=“enterText(this)”>click here</p>

Regular Expression Examples Identifier ^[a-zA-Z_$][a-zA-Z0-9_$]*$ Camel case identifier ^[a-z]+([A-Z][a-z]*)*$ Zipcode ^\d\d\d\d\d$, ^\d{5}$, ^[0-9]{5}$ Date ^1?\d\/\d?\d\/(\d\d|\d\d\d\d)$ Time ^1?\d(:[0-5]\d)?((a|p)m)?$

Metacharacters . any character except newline \n newline \d any digit \w any letter or digit \s whitespace (space, tab, newline, etc.) \D \W \S (not a digit, not a letter or digit, not whitespace) ^ the beginning of a string $ the end of a string \\ \. \^ \$ \/ \| \* \+ \? \( \) \{ \} \[ \] (\ . ^ $ / | * + ? ( ) { } [ ])

Regular Expressions regular-expression character-set regular-expression regular-expression regular-expression “|” regular-expression regular-expression (“*” | “+” | “?” | “{” int (“,” int)? “}”) “(” regular-expression “)” character (non metacharacter) metacharacter “[” “^”? (character (“-” character))*) “]”

Using Regular Expressions Regular expression objects var hatpat = new RegExp(hat, modifiers); var zipcode = /^\d{5}$/; Modifiers (optional) i ignore case m multiline match Use regularExpression.test(text) (true, if text contains a match to patten) if (hatpat.test(“this or that”)) return;

Block A sequence of statements packaged into one A block can be used anywhere a statement can { statement1 statement2 … statementn }

Conditionals Conditional Expressions Conditional Statements cond ? expr1 : expr2 Conditional Statements if ( cond ) statement statement1 else statement2

Repetition while loops for loops while ( cond ) statement var i=0 ; while (i<a.length) { a[i] = a[i]*a[i] ; i = i+1 ; } for loops for ( init ; cond ; inc ) statement for ( var i=0 ; i<a.length ; i = i+1 )