CSE 154 LECTURE 7: THE DOCUMENT OBJECT MODEL (DOM); UNOBTRUSIVE JAVASCRIPT.

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

24-Aug-14 HTML Forms. 2 What are forms? is just another kind of HTML tag HTML forms are used to create (rather primitive) GUIs on Web pages Usually the.
HTML – A Brief introduction Title of page This is my first homepage. This text is bold  The first tag in your HTML document is. This tag tells your browser.
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
Tutorial 6 Creating a Web Form
DOM and timers CS Problems with JavaScript JavaScript is a powerful language, but it has many flaws:  the DOM can be clunky to use  the same code.
HTML 5 and CSS 3, Illustrated Complete Unit L: Programming Web Pages with JavaScript.
Lesson 12- Unit L Programming Web Pages with JavaScript.
The Web Warrior Guide to Web Design Technologies
Chapter 6 Basic forms 1. Forms and query string 2 form : a group of user input (UI) controls that accepts information from the user and sends the information.
SE-2840 Dr. Mark L. Hornick 1 HTML input elements and forms.
Supplement Creating Forms. Objectives Show how forms are used How to create the Form element HTML elements used for creating input fields.
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
Form Basics CS Web Data  Most interesting web pages revolve around data  examples: Google, IMDB, Digg, Facebook, YouTube, Rotten Tomatoes  can.
Tutorial 6 Forms Section A - Working with Forms in JavaScript.
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.
CSE 154 LECTURE 9: FORMS. Web data most interesting web pages revolve around data examples: Google, IMDB, Digg, Facebook, YouTube, Rotten Tomatoes can.
CST JavaScript Validating Form Data with JavaScript.
Tutorial #9 – Creating Forms. Tutorial #8 Review – Tables Borders (table, gridlines), Border-collapse: collapse; empty-cells: show; and rowspan, colspan.
Forms and Form Controls Chapter What is a Form?
DAT602 Database Application Development Lecture 14 HTML.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
DOM and timers CS Problems with JavaScript JavaScript is a powerful language, but it has many flaws:  the DOM can be clunky to use  the same code.
Unobtrusive JavaScript
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
CSE 154 LECTURE 19: EVENTS AND TIMERS. Anonymous functions function(parameters) { statements; } JS JavaScript allows you to declare anonymous functions.
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.
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
What is Java Script? An extension to HTML. An extension to HTML. Allows authors to incorporate some functionality in their web pages. (without using CGI.
Lecture # 6 Forms, Widgets and Event Handling. Today Questions: From notes/reading/life? Share Personal Web Page (if not too personal) 1.Introduce: How.
Tutorial 7 Creating Forms. Objectives Session 7.1 – Create an HTML form – Insert fields for text – Add labels for form elements – Create radio buttons.
1 JavaScript in Context. Server-Side Programming.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
 2008 Pearson Education, Inc. All rights reserved Introduction to XHTML.
CSE 154 LECTURE 18: THE DOCUMENT OBJECT MODEL (DOM); UNOBTRUSIVE JAVASCRIPT.
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
HTML Form Widgets. Review: HTML Forms HTML forms are used to create web pages that accept user input Forms allow the user to communicate information back.
Web Development 101 Presented by John Valance
HTML Forms. Slide 2 Forms (Introduction) The purpose of input forms Organizing forms with a and Using different element types to get user input A brief.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
Event-Driven Programming Chapter Page Section: Section or division of an HTML page Generic block element Example: What's the difference between.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Lecture 8: Events and timers
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
20-753: Fundamentals of Web Programming 1 Lecture 6: Advanced HTML Fundamentals of Web Programming Lecture 6: Advanced HTML.
Internet & World Wide Web How to Program, 5/e Copyright © Pearson, Inc All Rights Reserved.
JQUERY AND AJAX
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
CSE 154 LECTURE 9: THE DOM TREE. The DOM tree The elements of a page are nested into a tree-like structure of objects the DOM has properties and methods.
Tutorial 6 Creating a Web Form
HTML Tutorial. What is HTML HTML is a markup language for describing web documents (web pages) HTML documents are described by HTML tags Each HTML tag.
FORMS Explained By: Jasdeep Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
COM621: Advanced Interactive Web Development Lecture 6 – JavaScript (cont.)
Tarik Booker CS 120 California State University, Los Angeles.
XHTML Forms.
Introduction to.
Lecture 7: The Document Object Model (DOM); Unobtrusive JavaScript
Lecture 9: Events and timers
Web Programming A different world! Three main languages/tools No Java
Event Driven Programming & User Defined Functions
Lecture 7: Unobtrusive JavaScript
Lecture 8: Events and timers
Lecture 7: Unobtrusive JavaScript
Web Programming and Design
Presentation transcript:

CSE 154 LECTURE 7: THE DOCUMENT OBJECT MODEL (DOM); UNOBTRUSIVE JAVASCRIPT

Event-driven programming JS programs have no main ; they respond to user actions called events event-driven programming: writing programs driven by user events

Event handlers... HTML Click me! HTML JavaScript functions can be set as event handlers when you interact with the element, the function will execute onclick is just one of many event HTML attributes we'll use onclick

Document Object Model (DOM)DOM a set of JavaScript objects that represent each element on the page each tag in a page corresponds to a JavaScript DOM object JS code can talk to these objects to 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

DOM element objects access/modify the attributes of a DOM object with objectName. attribute Name most DOM object attributes have the same names as the corresponding HTML attribute img tag's src property a tag's href property

DOM object properties See our Sales today! HTML var mainDiv = document.getElementById("main"); var icon = document.getElementById("icon"); var theLink = document.getElementById("saleslink"); JS PropertyDescriptionExample tagNameelement's HTML tagmainDiv.tagName is "DIV" classNameCSS classes of elementmainDiv.className is "foo bar" innerHTMLcontent in elementmainDiv.innerHTML is "\n See our <a hr... srcURL target of an imageicon.src is "images/borat.jpg" hrefURL target of a linktheLink.href is "sale.html"

Text fields: NetID Password HTML output input attributes: disabled, maxlength, readonly, size, value size attribute controls onscreen width of text field maxlength limits how many characters user is able to type into field

Text boxes: a multi-line text input area (inline) Type your comments here. HTML initial text is placed inside textarea tag (optional) required rows and cols attributes specify height/width in characters optional readonly attribute means text cannot be modified output

DOM properties for form controls Freshman? HTML var sid = document.getElementById("sid"); var frosh = document.getElementById("frosh"); JS output PropertyDescriptionExample valuethe text/value chosen by the usersid.value could be " " checkedwhether a box is checkedfrosh.checked is true disabledwhether a control is disabled (boolean)frosh.disabled is false readOnlywhether a text box is read-onlysid.readOnly is false

Adjusting styles with the DOM objectName.style.propertyName = "value"; JS Click me! Don't forget your homework! HTML function colorIt() { var text = document.getElementById("fancytext"); text.style.color = "#ff5500"; text.style.fontSize = "40pt"; } JS output PropertyDescription stylelets you set any CSS style property for an element same properties as in CSS, but with camelCasedNames, not names-with-underscores examples: backgroundColor, borderLeftWidth, fontFamily

Common DOM styling errors many students forget to write.style when setting styles var clickMe = document.getElementById("clickme"); clickMe.color = "red"; clickMe.style.color = "red"; JS style properties are capitalized likeThis, not like-this clickMe.style.font-size = "14pt"; clickMe.style.fontSize = "14pt"; JS style properties must be set as strings, often with units at the end clickMe.style.width = 200; clickMe.style.width = "200px"; clickMe.style.padding = "0.5em"; JS write exactly the value you would have written in the CSS, but in quotes

Unobtrusive JavaScript JavaScript event code seen previously was obtrusive, in the HTML; this is bad style now we'll see how to write unobtrusive JavaScript codeunobtrusive JavaScript HTML with no JavaScript code inside the tags uses the JS DOM to attach and execute all JavaScript event handlers allows separation of web site into 3 major categories:separation content (HTML) - what is it? presentation (CSS) - how does it look? behavior (JavaScript) - how does it respond to user interaction?

Obtrusive event handlers (bad) OK HTML // called when OK button is clicked function okayClick() { alert("booyah"); } JS this is bad style (HTML is cluttered with JS code) goal: remove all JavaScript code from the HTML body output

Attaching an event handler in JavaScript code objectName.onevent = function; JS OK HTML var okButton = document.getElementById("ok"); okButton.onclick = okayClick; JS it is legal to attach event handlers to elements' DOM objects in your JavaScript code notice that you do not put parentheses after the function's name this is better style than attaching them in the HTML

When does my code run?... HTML var x = 3; function f(n) { return n + 1; } function g(n) { return n - 1; } x = f(x); JS your file's JS code runs the moment the browser loads the script tag any variables are declared immediately any functions are declared but not called, unless your global code explicitly calls them at this point in time, the browser has not yet read your page's body none of the DOM objects for tags on the page have been created yet

A failed attempt at being unobtrusive OK HTML var ok = document.getElementById("ok"); ok.onclick = okayClick; // error: null JS problem: global JS code runs the moment the script is loaded script in head is processed before page's body has loaded no elements are available yet or can be accessed yet via the DOM we need a way to attach the handler after the page has loaded...

The window.onload event function functionName() { // code to initialize the page... } // run this function once the page has finished loading window.onload = functionName; there is a global event called window.onload event that occurs at the moment the page body is done being loaded if you attach a function as a handler for window.onload, it will run at that time

An unobtrusive event handler OK HTML // called when page loads; sets up event handlers function pageLoad() { var ok = document.getElementById("ok"); // (3) ok.onclick = okayClick; } function okayClick() { alert("booyah"); // (4) } window.onload = pageLoad; // (2) JS output

Common unobtrusive JS errors event names are all lowercase, not capitalized like most variables window.onLoad = pageLoad; window.onload = pageLoad; you shouldn't write () when attaching the handler (if you do, it calls the function immediately, rather than setting it up to be called later) ok.onclick = okayClick(); ok.onclick = okayClick;  our JSLint checker will catch this mistake related: can't directly call functions like alert ; must enclose in your own function ok.onclick = alert("booyah"); ok.onclick = okayClick; function okayClick() { alert("booyah"); }

Anonymous functions function(parameters) { statements; } JS JavaScript allows you to declare anonymous functions quickly creates a function without giving it a name can be stored as a variable, attached as an event handler, etc.

Anonymous function example window.onload = function() { var ok = document.getElementById("ok"); ok.onclick = okayClick; }; function okayClick() { alert("booyah"); } JS output or the following is also legal (though harder to read and bad style): window.onload = function() { document.getElementById("ok").onclick = function() { alert("booyah"); };

Unobtrusive styling function okayClick() { this.style.color = "red"; this.className = "highlighted"; } JS.highlighted { color: red; } CSS well-written JavaScript code should contain as little CSS as possible use JS to set CSS classes/IDs on elements define the styles of those classes/IDs in your CSS file

The danger of global variables var count = 0; function incr(n) { count += n; } function reset() { count = 0; } incr(4); incr(2); console.log(count); JS globals can be bad; other code and other JS files can see and modify them How many global symbols are introduced by the above code? 3 global symbols: count, incr, and reset

Enclosing code in a function function everything() { var count = 0; function incr(n) { count += n; } function reset() { count = 0; } incr(4); incr(2); console.log(count); } everything(); // call the function to run the code the above example moves all the code into a function; variables and functions declared inside another function are local to it, not global How many global symbols are introduced by the above code? 1 global symbol: everything (can we get it down to 0?)

The "module pattern" (function() { statements; })(); JS wraps all of your file's code in an anonymous function that is declared and immediately called 0 global symbols will be introduced! the variables and functions defined by your code cannot be messed with externally

Module pattern example (function() { var count = 0; function incr(n) { count += n; } function reset() { count = 0; } incr(4); incr(2); console.log(count); })(); JS How many global symbols are introduced by the above code? 0 global symbols

JavaScript "strict" mode "use strict"; your code... writing "use strict"; at the very top of your JS file turns on strict syntax checking: shows an error if you try to assign to an undeclared variable stops you from overwriting key JS system libraries forbids some unsafe or error-prone language features You should always turn on strict mode for your code in this class!

Checkboxes: yes/no choices that can be checked and unchecked (inline) Lettuce Tomato Pickles HTML none, 1, or many checkboxes can be checked at same time when sent to server, any checked boxes will be sent with value on: use checked="checked" attribute in HTML to initially check the box output

Radio buttons: sets of mutually exclusive choices (inline) Visa MasterCard American Express HTML output grouped by name attribute (only one can be checked at a time) must specify a value for each one or else it will be sent as value on

Text labels: Visa MasterCard American Express HTML associates nearby text with control, so you can click text to activate control can be used with checkboxes or radio buttons label element can be targeted by CSS style rules output

Drop-down list:, menus of choices that collapse and expand (inline) Jerry George Kramer Elaine HTML option element represents each choice select optional attributes: disabled, multiple, size optional selected attribute sets which one is initially chosen output

Using for lists Jerry George Kramer Elaine Newman HTML optional multiple attribute allows selecting multiple items with shift- or ctrl- click must declare parameter's name with [] if you allow multiple selections option tags can be set to be initially selected output

Option groups: Jerry George Kramer Elaine Newman Susan HTML What should we do if we don't like the bold appearance of the optgroup s? output

Grouping input:, groups of input fields with optional caption (block) Credit cards: Visa MasterCard American Express HTML fieldset groups related input fields, adds a border; legend supplies a caption output

Styling form controls element[attribute="value"] { property : value;... property : value; } CSS input[type="text"] { background-color: yellow; font-weight: bold; } CSS attribute selector: matches only elements that have a particular attribute value useful for controls because many share the same element (input) output

More about form controls James T. Kirk Jean-Luc Picard Benjamin Cisco I'm a Trekkie HTML output when talking to a text box or select, you usually want its value when talking to a checkbox or radio button, you probably want to know if it's checked (true/false)

The innerHTML property Click me! Hello HTML function addText() { var span = document.getElementById("output"); span.innerHTML += " bro"; } JS output can change the text inside most elements by setting the innerHTML property

Abuse of innerHTML // bad style! var paragraph = document.getElementById("welcome"); paragraph.innerHTML = " text and link "; JS innerHTML can inject arbitrary HTML content into the page however, this is prone to bugs and errors and is considered poor style we forbid using innerHTML to inject HTML tags; inject plain text only (later, we'll see a better way to inject content with HTML tags in it)