JavaScript Handling Events Page 1

Similar documents
JAVASCRIPT BASICS. Handling Events In JavaScript. In programing, event-driven programming could be a programming

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli

Fundamentals of Website Development

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore

Events: another simple example

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

JavaScript is described in detail in many books on the subject, and there is excellent tutorial material at

Catching Events. Bok, Jong Soon

Want to add cool effects like rollovers and pop-up windows?

JavaScript and Events

Introduction to DHTML

HTML User Interface Controls. Interactive HTML user interfaces. Document Object Model (DOM)

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

COMP519 Web Programming Lecture 16: JavaScript (Part 7) Handouts

Princeton University COS 333: Advanced Programming Techniques A Subset of JavaScript

Key features. Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages

TEXTAREA NN 2 IE 3 DOM 1

CISH-6510 Web Application Design and Development. Overview of JavaScript. Overview

DOM Primer Part 2. Contents

Skyway Builder Web Control Guide

Outline. Lecture 4: Document Object Model (DOM) What is DOM Traversal and Modification Events and Event Handling

Photo from DOM

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

Window Interface. get only ApplicationCache window.applicationcache. get only boolean window.closed

JavaScript: Events, DOM and Attaching Handlers

Installation and Configuration Manual

CSC Javascript

UNIT - III. Every element in a document tree refers to a Node object. Some nodes of the tree are

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2) What is JavaScript?

CSI 3140 WWW Structures, Techniques and Standards. Browsers and the DOM

Beijing , China. Keywords: Web system, XSS vulnerability, Filtering mechanisms, Vulnerability scanning.

JSF - H:INPUTSECRET. Class name of a validator that s created and attached to a component

Continues the Technical Activities Originated in the WAP Forum

Hell is other browsers - Sartre. The touch events. Peter-Paul Koch (ppk) WebExpo, 24 September 2010

Place User-Defined Functions in the HEAD Section

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

CITS3403 Agile Web Development Semester 1, 2018

Hell is other browsers - Sartre. The touch events. Peter-Paul Koch (ppk) DIBI, 28 April 2010

Dynamic Web Pages - Integrating JavaScript into a SAS Web Application Caroline Bahler, ASG, Inc.

Canvas & Brush Reference. Source: stock.xchng, Maarten Uilenbroek

Web Development & Design Foundations with HTML5, 8 th Edition Instructor Materials Chapter 14 Test Bank

Session 6. JavaScript Part 1. Reading

link document.getelementbyid("coffee").style.borderwidth = "0px" document.getelementbyid("tea").style.borderwidth = "10px"

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Web Site Development with HTML/JavaScrip

Client vs Server Scripting

Web Design. Lecture 6. Instructor : Cristina Mîndruță Site : Cristina Mindruta - Web Design

The first sample. What is JavaScript?

1$ 5 ! $ 6 4 * Source: 0 "!*! 0! * 8 97 ?!$ 5 0 *! 4! $ 0 : * ' () 7;7 7<7

JS Tutorial 3: InnerHTML Note: this part is in last week s tutorial as well, but will be included in this week s lab

Javascript. A key was pressed OR released. A key was released. A mouse button was pressed.

Web Development & Design Foundations with HTML5

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

Name Related Elements Type Default Depr. DTD Comment

CSS The web browser uses its own resources, and eases the burden on the server. It has fewer features than server side scripting.

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

HTML5 MOCK TEST HTML5 MOCK TEST I

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

j I 8 EVENTS INTERACTI O NS EVENTS TRI GGER CODE RESPONDS CREATE EV ENTS CODE TO USERS

JAVASCRIPT FOR PROGRAMMERS

Hell is other browsers - Sartre. Ajax Workshop. Peter-Paul Koch (ppk) Fundamentos del Web, 28 October 2008

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

JavaScript: A Crash Course

XHTML Mobile Profile. Candidate Version Feb Open Mobile Alliance OMA-TS-XHTMLMP-V1_ C

CSE 154 LECTURE 10: MORE EVENTS

Session 16. JavaScript Part 1. Reading

New Media Production Lecture 7 Javascript

This tutorial has been designed for beginners in HTML5 to make them understand the basicto-advanced

JSF - H:SELECTONEMENU

HTML 5 and CSS 3, Illustrated Complete. Unit L: Programming Web Pages with JavaScript

Introduction to JavaScript, Part 2

INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 15: JavaScript loops, Objects, Events - Spring 2011

Produced by. App Development & Modeling. BSc in Applied Computing. Eamonn de Leastar

JavaScript Introduction

Javascript Lecture 23

Dynamic HTML becomes HTML5. HTML Forms and Server Processing. Form Submission to Web Server. DHTML - Mouse Events. CMST385: Slide Set 8: Forms

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p.

MooTools 1.2. Jacob Gube Garrick Cheung. Chapter No. 5 "Working with Events"

Introduction to JavaScript

Introduction to using HTML to design webpages

Web Engineering (Lecture 06) JavaScript part 2

By the end of this section of the practical, the students should be able to:

Chapter 14 - Dynamic HTML: Event Model


JavaScript Programming

HTML and JavaScript: Forms and Validation

HTML5 and CSS3 The jquery Library Page 1

JSF - H:PANELGRID. JSF Tag. Rendered Output. Tag Attributes. The h:panel tag renders an HTML "table" element. Attribute & Description.

Creating Web Pages with HTML-Level III Tutorials HTML 6.01

CICS 515 a Internet Programming Week 3. Mike Feeley

JSF - H:SELECTONERADIO

NEW WEBMASTER HTML & CSS FOR BEGINNERS COURSE SYNOPSIS

Such JavaScript Very Wow

Programming the Web VALIDATING FORM INPUT

Q1. What is JavaScript?

Ajax in Practice by Dave Crane Bear Bibeault Jord Sonneveld with Ted Goddard, Chris Gray, Ram Venkataraman and Joe Walker

Proposal for Virtual Web Browser by Using HTML5

JavaScript II CSCI 311 SPRING 2017

Transcription:

JavaScript Handling Events Page 1 1 2 3 4 5 6 7 8 Handling Events JavaScript JavaScript Events (Page 1) An HTML event is something interesting that happens to an HTML element Can include: Web document completes its loading The user moves the mouse over a hyperlink or some other object The user clicks the mouse on a button or other object The user strikes a key on the keyboard All GUI (graphical user interface) applications behave this way JavaScript Events (Page 2) A common way of dealing with these events is to use an event attribute of the HTML object and assign the function name as its value <htmlelement eventtype="functionname()"> <button onclick="gettime()"> The document Object Represents the Web page displayed in a browser Contains all Web page elements The getelementbyid() Method A method of the document object that returns the first element in a Web document with a matching ID attribute value document.getelementbyid("indentifier") The indentifier is the value of the ID attribute of an HTML element document.getelementbyid("time").innerhtml = time.tolocaletimestring(); The innerhtml property The innerhtml property sets or returns the HTML content (inner HTML) of an element The content between an opening and closing tag such as <p> or one of the heading tags htmlelement.innerhtml document.getelementbyid("time").innerhtml = time.tolocaletimestring(); The <button> Tag (Page 1) The <button> tag defines a clickable button Inside a <button> element can put content like text or images which appear on the button This is the primary difference between this element and buttons created with the <input> element The <button> Tag (Page 2) <button type="button">text or image on the button</button> <button type="button">click me</button> Tip: Always specify the type attribute for a <button> (different browsers have

JavaScript Handling Events Page 2 9 10 11 12 13 14 15 16 17 18 different default types for the <button> element) The onclick Event The event that occurs when an element is clicked Often used with a button but can be applied to most HTML elements <htmlelement onclick="functionname()"> <button onclick="gettime()"> events1.htm Assigning Code to Event Attributes Alternately a single JavaScript statement can be assigned as the event attribute value <htmlelement eventtype="javascript statement"> <button onclick="getelementbyid('time').innerhtml = Date()"> Single 'quotes' and double "quotes" can be used interchangeably in JavaScript events1a.htm Anonymous Functions (Page 1) Functions may be assigned to event properties of an object in a JavaScript statement Must follow the declaration of the object (HMTL element), so it needs to be in the <body> section inside a <script> block The function is considered anonymous since there is no name follow the keyword function() Anonymous Functions (Page 2) object.eventtype = function() { functioncode }; The functioncode is inside a set of {braces} and can be either the body of an actual function or a function call to the name of a separately defined function Anonymous Functions (Page 3) document.getelementbyid("timebutton").onclick = function() { gettime() }; The gettime() function may be defined in a <script> block either in this or another <script> block events1b.htm The addeventlistener() Method (Page 1) The method to attaches ( registers ) an event handler function to a specified element Not supported in Internet Explorer 8 and earlier versions, and Opera 6.0 and earlier versions An event object is passed to the function as the first parameter The addeventlistener() Method (Page 2) object.addeventlistener(eventtype, functionname); timebutton.addeventlistener("click", gettime); The on prefix of the event is eliminated, e.g. just click

JavaScript Handling Events Page 3 19 20 21 22 23 24 25 26 27 28 The parentheses following the function name are eliminated, e.g. just gettime events1c.htm The addeventlistener() Method (Page 3) The second argument as a complete function: timebutton.addeventlistener("click", function gettime() { var time = new Date(); document.getelementbyid("time").innerhtml = time.tolocaletimestring(); } ) events1d.htm The attachevent() Method (Page 1) The method to attaches ( registers ) an event handler function to a specified element Used for Internet Explorer 8 and earlier versions, and Opera 6.0 and earlier versions The attachevent() Method (Page 2) object.attachevent(eventtype, functionname); timebutton.attachevent("click", gettime); The on prefix of the event is eliminated, e.g. just click The parentheses following the function name are eliminated, e.g. just gettime events1e.htm The <input> Tag as a Text Field The <input> tag with attribute type= text creates a text field (textbox) into which the user can type text <input type="text"> <input type="text" id="fahrenheit"> The value Property The value property sets or returns the value of an element or option (the value sent to the server when the form is submitted) For a text field the value property is the text currently contained within the textbox object.value; var fahrenheit = document.getelementbyid("fahrenheit").value; events2.htm DOM Events The HTML DOM events allow JavaScript to register event handlers on elements in an HTML document Events normally are associated with functions so that the function does not execute until the event occurs, e.g. when a user clicks a button

JavaScript Handling Events Page 4 29 30 31 32 33 34 35 36 Tip: The event model was standardized by the W3C in DOM Level 2 Form Events (Page 1) Events triggered by actions inside an HTML form (applies to almost all HTML elements, but is most used in <form> elements): onblur occurs when an element loses the focus onchange occurs when the content of a form element, the selection, or the checked state have changed For <input>, <keygen>, <select>, and <textarea> onfocus occurs when an element gets the focus Form Events (Page 2) Events triggered by actions inside an HTML form (con.): onfocusin occurs when an element is just about to get the focus onfocusout occurs when an element is just about to lose the focus oninput occurs when an element gets user input oninvalid occurs when an element is invalid onreset occurs when a form is reset Form Events (Page 3) Events triggered by actions inside an HTML form (con.): onsearch occurs when the user writes something in a search field For <input="search > onselect occurs after the user selects some text For <input> and <textarea> onsubmit occurs when a form is submitted Creating a Selection List (Page 1) The <select> block creates a scrollable menu (drop-down list or list box) used to select from a list of choices The list is inserted into the menu within a series of option blocks Creating a Selection List (Page 2) <select id="identifier" attributes> <option value="value1">text1</option> <option value="value2">text2</option>... </select> The value attribute value of the option selected is the value for the <select> and is assigned to the name (variable) property when the form is submitted The text are values displayed in the selection list Creating a Selection List (Page 3) <select id="carselect"> <option value="ford">ford</option> <option value="honda">honda</option> <option value="toyota">toyota</option> <option value="chevy">chevy</option> <option value="mercedes">mercedes</option> </select> events3.htm The style Object

JavaScript Handling Events Page 5 37 38 39 40 41 42 43 Returns the collection of CSS style properties for an HTML element Each style property may be set or retrieved object.style.cssproperty document.getelementbyid("inputbox").style.backgroundcolor = "red"; events4.htm Window Events (Page 1) Represent events related to browser itself: onload occurs when a document and all its resources are fully loaded and displayed (the most important of all window events) Often used inside the <body> to execute a script once all content is completely loaded Can be used to check visitor s browser type (loads proper version of Web page accordingly) Also can be used to deal with cookies Window Events (Page 2) Represent events related to browser itself (con.): onunload occurs when user navigates away from current Web document onbeforeunload similar to unload but provides the user an opportunity to cancel closing browser window or navigation to another page (more on this to follow) Window Events (Page 3) Represent events related to browser itself (con.): onreadstatechange similar to load but before external resources are fully loaded onresize occurs when user resizes browser window onscroll occurs when user scrolls up or down in the browser window s scroll channel Additionally onfocus and onblur from the form events occur when the browser window receives or loses keyboard focus from the operating system The onbeforeunload Event (Page 1) The event occurs when the Web page is about to be unloaded and can cancel unloading Unlike the unload event, it displays a dialog window that gives the user an opportunity to cancel any one of the following: Close the browser window Reload the browser window Navigation to another Web page The onbeforeunload Event (Page 2) The standard message in the dialog window is something like: Are you sure you want to leave this page? This message cannot be removed An additional custom message can be added by the programmer as well The onbeforeunload Event (Page 3) object.onbeforeunload=function() { return functioncode }; The keyword return allows the function to return a value which in this case is Boolean (if false the Web document will not unload)

JavaScript Handling Events Page 6 44 45 46 47 48 49 50 51 document.getelementbyid("webdocument").onbeforeunload = function() { return unloadfunction() }; The onbeforeunload Event (Page 4) The event handler function requires a string return value that is part of the prompt Specifically the custom message that is displayed in the dialog window along with the standard message function unloadfunction() { return "Click one of the buttons below"; } The navigator Object (Page 1) The window.navigator object includes both methods and properties with information about a visitor s browser May be written without the window prefix, e.g.: navigator.appname The navigator Object (Page 2) Some navigator object members navigator.appname property that represents the app name of the browser IE11, Chrome, Firefox, and Safari return appname Netscape navigator.appcodename property that represents the app code name of the browser Chrome, Firefox, IE, Safari, and Opera return appcodename Mazilla The navigator Object (Page 3) Some navigator object members (con.): navigator.product property that represents the engine name of the browser navigator.appversion property that represents version information about the browser navigator.useragent property that represents additional version information about the browser The navigator Object (Page 4) Some navigator object members (con.): navigator.platform property that represents operating system (platform) of the browser navigator.language property that represents the browser language The navigator Object (Page 5) Some navigator object members (con.): navigator.cookieenabled property that represents a Boolean value (true or false) indicating if cookies are enabled for the browser navigator.javaenabled() method that returns a Boolean value (true or false) indicating if Java is enabled for the browser events5.htm Mouse Events (Page 1) Events triggered by a mouse action: onclick occurs when the user clicks on an element oncontextmenu occurs when the user right-clicks on an element to open a context menu ondblclick occurs when the user double-clicks on an element

JavaScript Handling Events Page 7 52 53 54 55 56 57 58 onmousedown occurs when the user presses a mouse button over an element Mouse Events (Page 2) Events triggered by a mouse action (con.): onmouseenter occurs when the pointer is moved onto an element onmouseleave occurs when the pointer is moved out of an element onmousemove occurs when the pointer is moving while it is over an element onmouseover occurs when the pointer is moved onto an element, or onto one of its children Mouse Events (Page 3) Events triggered by a mouse action (con.): onmouseout occurs when a user moves the mouse pointer out of an element, or out of one of its children onmouseup occurs when a user releases a mouse button over an element events6.htm Key Events Events triggered by pressing and releasing keys on the keyboard onkeydown occurs when the user is pressing a key (key is down) onkeypress occurs when the user presses a key (a complete press and release) onkeyup occurs when the user releases a key The event Object (Page 1) Every event call has a built-in event object as which can be passed as its first parameter object.event = function() { functionname(event) } The event argument is a programmer-defined name document.getelementbyid("numberinput").onkeypress = function() { numbersonly(event) } The event Object (Page 2) To use the event object, define it as a parameter in the called function header As before the event parameter is a programmer-defined name function functionname(event) { function numbersonly(event) { The event Object (Page 3) The properties for an event object are contingent on which is the event that has occurred Some objects for the onkeypress event are: event.ctrlkey returns a boolean value indicating if the <Control> key was down when the event occurred event.charcode returns a number which is the Unicode value of the key that was pressed event.keycode returns a number which identifies the unmodified value of the key that was pressed event.repeat returns a boolean value indicating if the key is being held down and

JavaScript Handling Events Page 8 59 automatically repeating The event Object (Page 4) A summary of most event object properties and methods can be found at: https://developer.mozilla.org/en-us/docs/web/api/event 60 61 62 63 64 65 KeyboardEvent charcode Property The charcode property returns the Unicode value (number) of the key that triggered the onkeypress event event.charcode if (event.charcode == 48) { E.g. Is it the digit 1? KeyboardEvent keycode Property The keycode property returns a number which identifies the unmodified value of the pressed key that triggered the onkeypress event event.keycode if (event.keycode == 48) { E.g. Is it the digit 1? events7.htm DOM Events (Page 1) The DOM Level 3 Events specification adds new elements and modifies other functionality: Deprecates a number of event types that were defined by Level 2 but never widely implemented (e.g. DOMActivate, DOMFocusIn, and DOMNodeInserted,) Standardizes the focusin and focusout events as bubbling alternatives to the focus and blur events Standardizes mouseenter and mouseleave events as nonbubbling alternatives to mouseover and mouseout DOM Events (Page 2) The DOM Level 3 Events specification adds new elements and modifies other functionality (con.): Standardized support for two-dimensional mouse wheels via the wheelevent Better support for text input events with a textinput event and with a new KeyboardEvent object that is passed as the argument to handlers for keydown, keyup, and keypress events (deprecated keypress in favor of textinput) DOM Events (Page 3) The DOM Level 3 Events specification adds new elements and modifies other functionality (con.): Simplifies keydown, keyup, and keypress events by adding new key and char properties to event object Both of these properties are strings. For key events that generate printable characters, key and char will be equal to the generated text For control keys, the key property will be a string like Enter, Delete or Left that identifies the key

JavaScript Handling Events Page 9 66 67 68 69 HTML5 Events (Page 1) Inclusion of <audio> and <video> elements for playing sound and video with long list of events: canplay,loadeddata, playing, stalled, canplaythrough, loadedmetadata, progress, suspend, durationchange, loadstart, ratechange, timeupdate, emptied, pause, seeked, volumechange, ended, play, seeking, waiting HTML5 Events (Page 2) Drag-and-drop API allows JavaScript apps to participate in OS-based drag-and-drop operations: dragstart, drag, dragend, dragenter, dragover, dragleave, drop Defines a lot of new features for HTML forms including standardizing the form input event and defining a form validation mechanism HTML5 Events (Page 3) Support for offline web applications that can be installed locally in an application cache offline, online, cached, checking, downloading, error, noupdate, obsolete, progress, updateready, message Touchscreen and Mobile Events (For some other time)