Objects and Events Week 5 INFM 603. Muddiest Points Commonly used functions.getElementById Recursion Hashing.

Slides:



Advertisements
Similar presentations
23-Aug-14 HTML/XHTML Forms. 2 What are forms? is just another kind of XHTML/HTML tag Forms are used to create (rather primitive) GUIs on Web pages Usually.
Advertisements

Computer and Communication Fundamental Basic web programming Lecture 8 Rina Zviel-Girshin.
JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
The Web Warrior Guide to Web Design Technologies
Web Infrastructure Week 3 INFM 603. The Key Ideas Questions Structured Programming Modular Programming Data Structures Object-Oriented Programming.
Data Structures Week 4 INFM 603. The Key Ideas Structured Programming  Modular Programming  Data Structures Object-Oriented Programming.
Object Oriented Programming Week 5 INFM 603. The Key Ideas Structured Programming Modular Programming Data Structures  Object-Oriented Programming.
Information Technology Center Hany Abdelwahab Computer Specialist.
Computer Science 103 Chapter 4 Advanced JavaScript.
CIS101 Introduction to Computing Week 10. Agenda Your questions Final exam and final project CIS101 Student Survey Class presentations: Your Mad Libs.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
Forms, Validation Week 7 INFM 603. Announcements Try placing today’s example in htdocs (XAMPP). This will allow you to execute examples that rely on PHP.
CST JavaScript Validating Form Data with JavaScript.
1 Events Lect 8. 2 Event-driven Pages one popular feature of the Web is its interactive nature e.g., you click on buttons to make windows appear e.g.,
DOM, Content Management Systems, Drupal, Object- Oriented Design Week 8 INFM 603.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
4-Sep-15 HTML Forms Mrs. Goins Web Design Class. Parts of a Web Form A Form is an area that can contain Form Control/Elements. Each piece of information.
JS: DOM Form Form Object Form Object –The Form object represents an HTML form. –For each instance of a tag in an HTML document, a Form object is created.
JavaScript and The Document Object Model MMIS 656 Web Design Technologies Acknowledgements: 1.Notes from David Shrader, NSU GSCIS 2.Some material adapted.
1 Forms A form is the usual way that information is gotten from a browser to a server –HTML has tags to create a collection of objects that implement this.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
Event Handlers CS101 Introduction to Computing. Learning Goals Learn about event handlers Determine how events are useful in JavaScript Discover where.
Structured Programming Week 3 INFM 603. Muddiest Points Emergent behavior of the Web HTML class attribute The details of JavaScript … p.style1 { font-family:arial;
Functions and Data Structures Week 4 INFM 603. Programming in Four Parts Structured Programming  Data Structures  Modular Programming Object-Oriented.
The Document Object Model. Goals Understand how a JavaScript can communicate with the web page in which it “lives.” Understand how to use dot notation.
IT – som værktøj Bent Thomsen Institut for Datalogi Aalborg Universitet.
JavaScript Lecture 6 Rachel A Ober
Arrays – What is it? – Creation – Changing the contents Functions – What is it? – Syntax – How they work – Anonymous functions A quick lesson in Objects.
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.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Javascript II DOM & JSON. In an effort to create increasingly interactive experiences on the web, programmers wanted access to the functionality of browsers.
1 Forms and Form elements CSD 340 McCoey. 2 Form Object Properties action Usually a call to a server elements encoding method post or get target Methods.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Functions, Objects, and Programming IDIA 619 Spring 2014 Bridget M. Blodgett.
LOGO FORMs in HTML CHAPTER 5 Eastern Mediterranean University School of Computing and Technology Department of Information Technology ITEC229 Client-Side.
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
Introduction to the Document Object Model DOM *Understand document structure manipulation *Dynamic effects in web pages *Programming, scripting, web content.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
Scripting and Interactivity 이병희
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming control structures, events, objects.
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
IS2802 Introduction to Multimedia Applications for Business Lecture 3: JavaScript and Functions Rob Gleasure
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
Event Handling. Objectives Using event handlers Simulating events Using event-related methods.
INFM 603: Information Technology and Organizational Context Jimmy Lin The iSchool University of Maryland Thursday, October 9, 2014 Session 5: JavaScript.
Lesson 16. Practical Application 1 We can take advantage of JavaScript and the DOM, to set up a form so that the first text box of a form automatically.
Introduction to Programming the WWW I CMSC Summer 2003 Lecture 9.
Document Object Model Nasrullah. DOM When a page is loaded,browser creates a Document Object Model of the Page.
INFM 603: Information Technology and Organizational Context Jimmy Lin The iSchool University of Maryland Wednesday, February 19, 2014 Session 4: JavaScript.
JavaScript Event Handlers. Introduction An event handler executes a segment of a code based on certain events occurring within the application, such as.
JavaScript Events Java 4 Understanding Events Events add interactivity between the web page and the user You can think of an event as a trigger that.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
JavaScript Events. Understanding Events Events add interactivity between the web page and the user Events add interactivity between the web page and the.
Introduction to JavaScript Events Instructor: Sergey Goldman 1.
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
HTML Tables Tables are defined with the tag. A table is divided into rows (with the tag), and each row is divided into data cells (with the tag). td stands.
FORMS Explained By: Jasdeep Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
2440: 141 Web Site Administration Web Forms Instructor: Joseph Nattey.
Chapter 5 Validating Form Data with JavaScript
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
CHAPTER 7 JavaScripts & HTML Documents
Web Programming and Design
Presentation transcript:

Objects and Events Week 5 INFM 603

Muddiest Points Commonly used functions.getElementById Recursion Hashing

Programming in Four Parts Structured Programming Modular Programming Data Structures  Object-Oriented Programming

Key Ideas Protect the programmer from themselves –Model actions and attributes together Object –Encapsulation of methods and data structures Class –“Blueprint” for an object –Must be “instantiated” using a “constructor”

Objects: Methods It’s just a collection of properties! Objects can have functions also! (called methods) var fido = { name: "Fido", weight: 40, breed: "Mixed", loves: ["walks", "fetching balls"], bark: function() { alert("Woof woof!"); } };

Constructor function Dog(name, breed, weight) { this.name = name; this.breed = breed; this.weight = weight; this.bark = function() { if (this.weight > 25) { alert(this.name + " says Woof!"); } else { alert(this.name + " says Yip!"); } }; }

Using Constructors Invoke constructors using “new”: var fido = new Dog("Fido", "Mixed", 38); var tiny = new Dog("Tiny", "Chawalla", 8); var clifford = new Dog("Clifford", "Bloodhound", 65); fido.bark(); tiny.bark(); clifford.bark();

Properties and Methods Access object properties using the “dot” notation Invoke an object’s method using the dot notation: this.bark() fido.bark(); var w = fido.weight; fido.breed = "Yellow Lab";

Some Conventions CapsInitial camel case is used for a a class lowerCaseInitial camel case is used for a –Variable (if not followed by parameters) –Method (if followed by parameters) An object can be assigned to a variable

Object Instantiation var n = new Array(5); –Creates an Array object using the Array class constructor (and specifying 5 elements) var student = new Student(13205, “George”); –Creates a Student object using the Student class constructor (and specifying the student id and name) –Note that the variable name need not be different from (or the same as) the class name

Formalizing Object Interfaces status = student.setHeightInches(74); –Invokes the setHeightInches() method for the object that is stored in the variable student and passes it 74 as a parameter; status=true indicates success feet = student.getHeightFeet(); –Invokes the getHeightFeet() method for the object that is stored in the variable student and then sets the variable feet to hold that result (in this case, 6); feet<0 indicates failure

Class Definition (private variable) function Student(studentID, name) { var totalInches = -1; // private variable // private method function inchesToFeet(i) { return Math.floor(i/12); } // public methods this.setHeightInches = function(n) { if ((n>0) && (n<100)) { totalInches = n; return true; } else { return false; } this.getHeightFeet = function() { if (totalInches>0) { return inchesToFeet(totalInches); } else { return -1; } var student = new Student(13205, "George"); alert(student.setHeightInches(74)); alert(student.getHeightFeet()); alert(student.totalInches);

Class Definition (public variable) function Student(studentID, name) { this.totalInches = -1; // public variable // private method function inchesToFeet(i) { return Math.floor(i/12); } // public methods this.setHeightInches = function(n) { if ((n>0) && (n<100)) { this.totalInches = n; return true; } else { return false; } this.getHeightFeet = function() { if (this.totalInches>0) { return inchesToFeet(this.totalInches); } else { return -1; } var student = new Student(13205, "George"); alert(student.setHeightInches(74)); alert(student.getHeightFeet()); alert(student.totalInches);

function Student(studentID, name) { var inches = -1; // private variable var feet = -1; // private variable // private method function inchesToFeet(i) { return Math.floor(i/12); } // public methods this.setHeightInches = function(n) { if ((n>0) && (n<100)) { feet = inchesToFeet(n); inches = n-(feet*12); return true; } else { return false; } this.getHeightFeet = function() { if ((feet>0) || (inches>0)) { return feet; } else { return -1; } var student = new Student(13205, "George"); alert(student.setHeightInches(74)); alert(student.getHeightFeet()); alert(student.feet); Alternate Method Definition (private variables)

var student={name:"Ann", lastname:"Smith", age:28, program:["MIM","Data Analytics"]}; var student2={name:”Rob", lastname:“Rogers", age:32, program:["MLS",“UX"]}; document.writeln(" “ + student.program[1] + " “ + student2.program[1]); Alternative Notation

Everything is an Object var b = new Boolean(true); var n = new Number(3.15); var n = new Number(3); // same as 3.00 var a = new Array(5);

String Objects (Conceptually) an array of Unicode characters with some interfaces –var s = “Mr. Spock” –s.toLowerCase is “mr. spock” –s.substr(3,4) is “ Spo” –s.indexOf(“k”) is 8 –s.split(“ ”) is [“Mr.”, “Spock”] –s.link( is Mr. Spock –s + “Captain Kirk” is “Mr. SpockCaptainKirk”

Some Handy Methods document –document.writeln(“Test!”); –var e=document.getElementById(“goButton”); –document.cookie=“message=saveme”; –var c=document.cookie.split(“=“)[1]; window –window.prompt(“Input please”); –var w=window.open(“”, “New Window”, “”);

Some Math Methods Math.abs() – Absolute value –Example: Math.abs(-10) Math.max() – Maximum of two values –Example: Math.max(10, 20) Math.sqrt() – Square root –Example: Math.sqrt(4) Math.random() – Random value between 0 and less than 1 –Example: Math.random() Constants –Math.PI – Mathematical constant pi

Why Use Objects? A way of thinking about programming –Objects are nouns, methods are verbs A form of defensive programming –Hides private variables and methods –Allows you to make behaviors explicit Represent complex data structures –Airplanes have pilots, fuel, and destinations

Design Exercise Design a class for messages Private internal representation should include: –Header (date, time, sender, recipients, subject, …) –Body –Attachments (which may be other s!) Public interfaces should include –Message creation –Access to specific header fields, the body, and specific attachments

The Document Object Model (DOM) Source:

The Document Object Model (DOM) Source:

document Source: headbody h1ppul li

A DOM Tree

Document Object Model The DOM view of an HTML page has: – OBJECTS: HTML elements – ATRIBUTES of the elements – METHODS to access elements – EVENTS to control elements

Getting to DOM Elements

Asking the DOM to “do stuff” document.method(“argument”); document represents the entire page and contains the DOM the method is want you want the document “to do”, usually a verb phrase arguments are additional details that you specify document.writeln(“Hello World”);

Access to DOM Elements Find a single element element = document.getElementById(“input2”); Find multiple elements list = document.getElementsByTagName(input); list = document.getElementsByName(“myInput”); Move up in the DOM tree –element1 = element2.parentNode; Move down in the DOM tree –list = element1.childNodes

DOM: Selecting an Element/Node Get Element by ID: Hello World! var text= document.getElementById("intro"); text.innerHTML;

DOM: Selecting an Element/Node Get Element by ID: Hello World! var text= document.getElementById("intro"); text.innerHTML; Get Element Change text in intro

DOM: Selecting an Element/Node Get Element by Tag: Hello World! document.getElementsByTagName(“p");  returns collection of “p”s in HTML (array with intro1 and intro2)

Line Zero Line One Line Two var x=document.getElementById("main"); var y=document.getElementsByTagName("p"); document.write("Get element by id " + x.innerHTML +" "); for(c=0;c<3;c++){ document.write("Get element by tag " + y[c].innerHTML+" "); }

DOM: Manipulating Elements/Nodes Modify the document – document.write(“text”) Modify a node: – Content: document.getElementById(“p¨).innerHTML=“Hello”; – Attribute: document.getElementById(“image”).src=“newimage”; – Style: document.getElementById(“text¨).style.color=blue;

document.getElementById("image").src=“tea.jpg";

DOM: Manipulating Children Nodes Accessing child nodes: – element.childNodes(); document.getElementById("list").childNodes[1].innerHTML = "new item";

Example Line One Line two Write a JavaScript program that changes line two to font Arial and color blue

Line One Line Two document.getElementById("p2").style.color="blue"; document.getElementById("p2").style.fontFamily="Arial"; The paragraph above was changed by a script.

DOM: Create Elements/Nodes Create a new node: var p = document.createElement("p"); p.innerHTML = "here is some new text."; document.getElementById("div1").appendChild(p); Create item for a list: var newItem = document.createElement("li"); newItem.innerHTML = "new list item"; document.getElementById("list").appendChild(newItem);

Example Line One Line Two var para=document.createElement("p"); para.innerHTML=“Line Three”; var element=document.getElementById("div1"); element.appendChild(para);

DOM: Eliminate Elements/Nodes Select node to eliminate and remove it with removeChild: var list = document.getElementById("list"); var listItem = list.childNodes[1]; list.removeChild(listItem);

var con = document.getElementById("myTable"); var tab = document.createElement("table"); tab.setAttribute("border", "1"); var r,c,td,tr; for(r=1;r<5;r++){ tr = document.createElement("tr"); for (c=1;c<5;c++){ td = document.createElement("td"); td.innerHTML="Row"+r+"Col"+c; tr.appendChild(td); } tab.appendChild(tr); } con.appendChild(tab);

Documentation Tips Reflect your pseudocode in your code –Use meaningful variable names –Use functions for abstractable concepts And name those functions well –Use comments to fill remaining gaps Add a comment to identify each revision –Give author, date, nature of the change Waste space effectively –Use indentation and blank lines to guide the eye

Using JavaScript with Forms HTML: Please enter a number: The sum of all numbers up to the number above is JavaScript: var num = eval(document.input.number.value); document.output.number.value = 10; Reads in a value from the first form (eval method turns it into a number) Changes the value in the second form

HTML Form Element Types Textarea (multiple lines) Input –Text (single line) –Password (like text, but masked) –Hidden (like text, but not displayed at all) –Button –Checkbox (multiple selection) –Radio (single selection) Select (dropdown list) see for examples

Linking Forms to Functions Events: –Actions that users perform An “event handler” is triggered by an event –onClick: the user clicked on the item –onMouseover: the mouse moved onto the item –onMouseout: the mouse moved off of the item

Referring to Form Content Enter integer search key … var inputVal = document.getElementById("inputVal"); var searchKey = inputVal.value; Please enter your age … var age = document.years.box.value;

Events Events allow an HTML webpage to react to a users’ behavior (event handler) – Click of a mouse – Mouse over an element – User strokes a key – Image has been loaded – Input field is changed (forms)

More complex events…Forms Click on button to select an action Text box for entering a line of text Radio buttons for making one selection among a group of options Check boxes for selecting or deselecting a single, independent option Lists of things to select one

Push Button

Text Box This is a text area.

Radio Button Apples Oranges

Check Box I have a bike I have a car

List Oranges Apples Lemons Bananas

Handling Events…JavaScript! JavaScript is responsible for “doing things” when buttons are clicked <input type="button" value="This is a button" onclick="myFunction()">

Handling Events…JavaScript! <input type="button" value="This is a button" onclick="myJSFunction()"> function myJSFunction() { do something}

Example with Push Button function myJSFunction() { document.getElementById("demo").innerHTML="Hello World"; } Try this

Text Box: access text var textInput = document.getElementById("textInput"); var textValue = textInput.value; alert(textValue);

Text Box <body Forms function handleClick() { var textInput = document.getElementById("textInput"); USE THE DOM var textValue = textInput.value; alert("The input text is: " + textValue); }

Radio Button One Two var onechecked = document.getElementById("radioone").checked; alert(“button one checked: " + onechecked);

<body Forms function handleClick() { var onechecked = document.getElementById("radioone").checked; var twochecked = document.getElementById("radiotwo").checked; alert("one checked: " + onechecked+" two checked "+twochecked); } One Two

Check Box I have a dog var hasDog = document.getElementById("checkDog").checked;

<body Forms function handleClick() { var hasDog = document.getElementById("checkDog").checked; var hasCat = document.getElementById("checkCat").checked; alert("dog? " + hasDog+ " cat? " + hasCat); } I have a dog I have a cat

List Oranges var selectInput = document.getElementById("selectInput"); var selectedIndex = selectInput.selectedIndex; var selectedValue = selectInput.options[selectedIndex].value;

<body Forms function handleClick() { var selectInput = document.getElementById("selectInput"); var selectedIndex = selectInput.selectedIndex; var selectedValue = selectInput.options[selectedIndex].value; alert("Which fruit do you prefer? " + selectedValue); } Oranges Lemons Apples Bananas

Term Project Option 1: –Drupal, Joomla, … Option 2: Programming project –Javascript, PHP, Java, C, Python, Ruby, … Four “deliverables” –P1 requests teaming preferences Assigned based on skills diversity –P2 is project plan –P3 is project design –P4 is presentation slides (from class presentation)

Before You Go On a sheet of paper, answer the following (ungraded) question (no names, please): What was the muddiest point in today’s class?