JavaScript Events, Forms & AJAX
Basic Events Handling
General UI implementations : event-driven
Events are not always triggered by user
Basic event handling: HTML attributes or JavaScript properties
<button onClick="alert(typeof this.onclick);"/>
btnMy.onclick = function () { alert(this); };
String attribute value vs. function property JS property names always lower case this and scope chain Event handlers return values
Advanced Event Handling
Adopted with DOM Level 2, except for Internet Explorer Event object parameter or global and its properties
2 phase propagation: capture and bubble stopPropagation() and cancelBubble preventDefault() and returnValue Handler registration: addEventListener / attachEvent
addEventListener() and useCapture Handler scope: not augmented; this keyword in IE Multiple handlers and duplicate registrations Specialized events (mouse, key) have different properties Synthetic events with dispatchEvent / fireEvent
HTML Forms
Submit button or no submit button ?
Difference between HTTP GET and POST
Form properties:action, method, enctype, target, elements Useful events on form elements: click, change, select, focus, blur
Common element properties: type, form, name, value
Useful applications:
validate input values before submit filter keys input (e.g. only digits) dynamically creating select options prepare additional hidden fields
AJAX
What does it stand for ?
(Asynchronous JavaScript and XML)
HTTP scripting alternatives: img, iframe, script XMLHttpRequest, XDomainRequest and ActiveXObject (Msxml2|Microsoft).XMLHTTP 3 steps: create, send, receive Cross-platform object creation open(method, url, async) and send(body) Asynchronous receiving with onreadystatechange and readyState: status, responseText, responseXML
Manipulating headers with setRequestHeader / getResponseHeader; explicit contentType
Other event handlers: onerror, ontimeout, onprogress, onload
Recap and Homework
Create an HTML page with a FORM containing all kinds of form elements and JavaScript validation on submit Create an HTML page that sends asynchronous requests and displays a progress bar while loading response