DOM Events. JS Events Outline About Events – Introduction – Registering events – Getting information from events Event order/phases – Preventing default.

Slides:



Advertisements
Similar presentations
5.1 JavaScript Execution Environment
Advertisements

JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
CS7026 jQuery Events. What are Events?  jQuery is tailor-made to respond to events in an HTML page.  Events are actions that can be detected by your.
Chapter 6 © 2012 by Addison Wesley Longman, Inc Introduction Def: A dynamic HTML document is one whose tag attributes, tag contents, or element.
Event Handling. Overview How to listen (and not listen) for events Creating a utility library (and why you should) Typology of events Pairing event listeners.
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
Tutorial 15 Working with the Event Model. XP Objectives Compare the IE and W3C event models Study how events propagate under both event models Write a.
20-Jun-15 JavaScript and HTML Simple Event Handling.
Cos 381 Day 7. © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Agenda Assignment one graded –Did not see any big issues »Some still have issues.
Cos 381 Day 7. © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Agenda Assignment 2 Posted –Program a web-based Version of Soduku using JavaScript.
Lesson 2 Event Handling. Object Event Handlers Most of the objects that make up the Document Object Model respond to asynchronous, user generated events.
JavaScript Client Side scripting. Client-side Scripts Client-side scripts, which run on the user’s workstation can be used to: Validate user inputs entered.
UNIT 6 JAVASCRIPT EVENT HANDLERS &WEB BROWSERS DETECTION.
CP476 Internet Computing JavaScript and HTML1 1.JavaScript Execution Environment The JavaScript Window object represents the window in which the browser.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Event and Event Handling.
Event Handlers CS101 Introduction to Computing. Learning Goals Learn about event handlers Determine how events are useful in JavaScript Discover where.
Chapter 5 © 2003 by Addison-Wesley, Inc. 1 Chapter 5 JavaScript and HTML Documents.
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
Chapter 5 JavaScript and HTML Documents. © 2006 Pearson Addison-Wesley. All rights reserved JavaScript Execution Environment - The JavaScript.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 JavaScript and HTML Documents.
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.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
CO1552 Web Application Development HTML Forms, Events and an introduction to JavaScript.
DOM Events. JS Events Outline About Events – Introduction – Registering events – Getting information from events Event order/phases – Preventing default.
Intro to JavaScript Scripting language –ECMAScript compliant –Client side vs. server side Syntactic rules –White space –Statement end: ; optional –Comments:
Chapter 5 © 2005 by Addison Wesley Longman, Inc JavaScript Execution Environment - The JavaScript Window object represents the window in which the.
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
Events DOM Event Model. HTML Events "on" + event name attribute value is javascript javascript runs 1st return false to STOP browser event (if any)
Event JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page. When the page loads, that is.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
Thursday, August 6 th, 2015 Instructor: Craig Duckett Event Handling.
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.
Project 8: Reacting to Events Essentials for Design JavaScript Level One Michael Brooks.
COS 125 DAY 20. Agenda Assignment 8 not corrected yet Assignment 9 posted  Due April 16 New course time line Discussion on Scripts 
Web Programming Java Script & jQuery Web Programming.
Dr. Ahmet Cengizhan Dirican BIL 374 Internet Technologies 5. JavaScript and HTML Documents.
7. JavaScript Events. 2 Motto: Do you think I can listen all day to such stuff? –Lewis Carroll.
H.Melikyan/4910/031 Programming the World Wide Web JavaScript Dr.Hayk Melikyan Departmen of Mathematics and CS JavaScript and HTML Documents.
Chapter 6 © 2014 by Pearson Education Introduction Def: A dynamic HTML document is one whose tag attributes, tag contents, or element style properties.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
JavaScript Events.
JavaScript Event Handlers. Introduction An event handler executes a segment of a code based on certain events occurring within the application, such as.
Modern JavaScript Develop And Design Instructor’s Notes Chapter 8 – Event Handling Modern JavaScript Design And Develop Copyright © 2012 by Larry Ullman.
LESSON : EVENTS AND FORM VALIDATION -JAVASCRIPT. EVENTS CLICK.
Chapter 6 Dynamic Documents with JavaScript. © 2006 Pearson Addison-Wesley. All rights reserved Introduction Def: A dynamic HTML document is.
Jozef Goetz contribution, © by Pearson Education, Inc. All Rights Reserved.
Introduction to JavaScript Events Instructor: Sergey Goldman 1.
Internet & World Wide Web How to Program, 5/e.  JavaScript events  allow scripts to respond to user interactions and modify the page accordingly  Events.
Chapter 6 © 2003 by Addison-Wesley, Inc Introduction - Dynamic HTML is not a new markup language - A dynamic HTML document is one whose tag attributes,
SE-2840 Dr. Mark L. Hornick 1 Dynamic HTML Handling events from DOM objects.
6.1 Introduction 6.2 Element Positioning
5.1 JavaScript Execution Environment
JavaScript and HTML Simple Event Handling 11-May-18.
Introduction to JavaScript Events
JAVASCRIPTS AND HTML DOCUMENTS
JavaScript and Events.
JavaScript and HTML Simple Event Handling 19-Sep-18.
CSE 154 Lecture 11: More Events.
JavaScript and HTML Documents
Events.
Introduction to jQuery
JavaScript and Events CS Programming Languages for Web Applications
5.1 JavaScript Execution Environment
JavaScript and Ajax (JavaScript Events)
CHAPTER 6 EVENTS. CHAPTER 6 EVENTS WHAT IS AN EVENT?
6.1 Introduction 6.2 Positioning Elements
JavaScript and HTML Simple Event Handling 26-Aug-19.
JavaScript and Events CS Programming Languages for Web Applications
JavaScript and HTML Simple Event Handling 4-Oct-19.
Presentation transcript:

DOM Events

JS Events Outline About Events – Introduction – Registering events – Getting information from events Event order/phases – Preventing default action – Preventing bubble Events in detail – Click – Keyboard – Mouse

DOM Events An event system that allows registration of event listeners Describes event flow through a tree structure Provide a common subset of current event systems used in existing browsers.

What are events? Events occur when some type of interaction takes place in a web page. (Mouse click, mouse move, key press, etc) Events are also things that happen to the web browser. (Loading a page, window resize, scroll window) With javascript, developers can detect when certain events happen, and cause things to happen in response. CSE 33454

How events work Events can be registered to HTML elements, window, and document objects. When an event happens on an element, the web page checks to see if the element has any event handlers attached. If it does, the webpage will call registered event handlers with references and info for each event that occurred. Event handlers then act upon the event with whatever code is specified by the developer. CSE 33455

Event Example Example 1 Say hello Example 2 var link = documents.getElementsByTagName(“a”)[0]; link.addEventListener(“click”, function(event) { alert(“Hello”); }, false); CSE 33456

Evolution of Events In the early days, events use to be handled directly by HTML elements. Uses inline javascript which is very messy and didn’t allow reusability. Say hello CSE 33457

Inline Javascript events onclick ondblclick onmousedown onmousemove onmouseover onmouseout onmouseup onkeydown onkeypress onkeyup onabort onerror onload onresize onscroll onunload onblur onchange onfocus onreset onselect onsubmit CSE 33458

Next step in event evolution Apply events in blocks of javascript code. Code can now be cached and is reusable. document.getElementById("my-link").onclick = waveToAudience; function waveToAudience() { alert("Waving like I've never waved before!"); } My link CSE 33459

Inline Javascript events You can get/set events using DOM Each event has an associated node property Properties get overwritten when new values are given. document.body.onclick = function(event) {return 1;} document.body.onclick = function(event) {return 2;} //overidding any previously set onclick values CSE

Later step in event evolution Introduced in DOM 2 Event spec Created addEventListener() and removeEventListener() Allows developers to register and remove listeners on elements CSE

addEventListeners() Has three parameters 1.type 2.listener 3.useCapture document.body.addEvent(type, listener, useCapture); CSE

addEventListener() example document.body.addEventListener('click', function (event) { console.log("hello"); }, false); document.body.addEventListener('click', function(event) { console.log("world");}, false); CSE type listener useCapture

addEventListener() For the type parameter, you don’t need to prepend the “on” for each event type. Using addEventListener(), event handlers AREN’T overwritten. – That means you can have multiple listeners on the same element. CSE

Type values click dblclick mousedown mousemove mouseover mouseout mouseup keydown keypress keyup abort error load resize scroll unload blur change focus reset select submit CSE

removeEventListener() example Has three parameters 1.type 2.listener 3.useCapture document.body.removeEventListener('click', function(event) { console.log("hello"); }, false); document.body.removeEventListener('click', function(event) { console.log("world");}, false); Calling removeEventListener() with arguments which do not identify any currently registered event handlers on a target has no effect. CSE

Your turn! Add a click listener to an element so that each time the element is clicked, its top increases by 10px. document.body.style.top = "0px"; document.body.style.top;// "0px"; CSE

Window load Event Javascript has a window object that represents an open window in a browser. The window’s load event is triggered when the complete document (DOM) is loaded. – This includes images and elements We should put all logic that deals with accessing the DOM in the window’s load event listener. CSE

Window load event example window.addEventListener('load', function(event) { //You should put all javascript logic that access nodes in the DOM inside //this event listener var element = document.getElementById("content"); element.style.color = "rgb(255,255,255); }, false); CSE

Getting information from an event The Event interface provides basic contextual information about an event to all registered event handlers.event handlers Supply a parameter to your event handler or use the arguments method to access the Event interface. CSE

Getting information from an event function clickHandler(event) { if (event !== undefined) { console.log(event.timeStamp); // console.log(event.type); //click console.log(event.target); // } document.body.addEventListener('click', clickHandler, false); CSE Event interface

CSE interface Event { // PhaseType const unsigned short NONE = 0; const unsigned short CAPTURING_PHASE = 1; const unsigned short AT_TARGET = 2; const unsigned short BUBBLING_PHASE = 3; readonly attribute DOMString type; readonly attribute EventTarget? target; readonly attribute EventTarget? currentTarget; readonly attribute unsigned short eventPhase; readonly attribute boolean bubbles; readonly attribute boolean cancelable; readonly attribute DOMTimeStamp timeStamp; void stopPropagation(); void preventDefault(); void initEvent(DOMString eventTypeArg, boolean canBubbleArg, boolean cancelableArg); // Introduced in DOM Level 3: void stopImmediatePropagation(); readonly attribute boolean defaultPrevented; readonly attribute boolean isTrusted; };

Important Event Interface variables type – the name of the event type (click, focus, blur, etc.) target – the object the event happened on currentTarget – the object associated with the event handler currently being handled. CSE

JS Events Outline About Events – Introduction – Registering events – Getting information from events Event order/phases – Preventing default action – Preventing bubble Events in detail – Click – Keyboard – Mouse

Event Order There are 2 types of event orders: event capturing and event bubbling. CSE

Event Capturing Event order starts with the outer most element in the DOM The webpage then begins working its way inward to the HTML element the event took place on. Event listeners registered for this phase must handle the event before it reaches its target. CSE

Event Bubbling Works in the opposite manner of event capturing. A webpage starts looking for event handlers on the targeted html element (where the event occurred) and then bubbles up to the top of the document. Event listeners registered for this phase must handle the event after it has reached its target. CSE

W3C Model Allows developers to decide how event order should be handled. Combines both event capturing and event bubbling. CSE

CSE W3C Event Model

Target Phase Handling the event must happen when the event reaches the target.

Specifying which event order When using the addEventListener() method, you can specify the event order with the useCapture parameter. useCapture === true will specify the event order to be capture. useCapture === false will specify the event order to be bubble. CSE

Event Order Demo CSE

Bubble is used more often than capture In practice people rarely use the capture phase, but there are still times when it might be useful. CSE

Default Events Handler Some elements have default event handlers: – navigates to specified href/anchor – submits a form for you – give focus to the corresponding input element CSE

What if I want to stop default handlers? It is possible to stop the default action of an element in your event handler. This might be useful for doing client side validation before submitting a form, preventing a user from navigating to a certain link, etc. CSE

How to stop the default action Using the Event interface object, call the preventDefault() method. CSE

Stop the link var links = document.getElementsByTagName("a"); for (var i=0; i<links.length; i++) { links[i].onclick = function (e) { alert("NOPE! I won't take you there!, I’m calling preventDefault()"); e.preventDefault(); }; } CSE

What if I want to stop event bubbling? While handling an event, it is possible to prevent ancestor event handlers from receiving events by cancelling the bubble. Use the Event interface’s stopPropagation() method. CSE

Stop bubbling example div.addEventListener('click', function(e) { console.log("I'm going to prevent this event from bubbling up!!!"); e.stopPropagation(); } }, false); CSE

JS Events Outline About Events – Introduction – Registering events – Getting information from events Event order/phases – Preventing default action – Preventing bubble Events in detail – Click – Keyboard – Mouse

Quickfacts about click events A click event is fired only if a mousedown AND mouseup event happen on an element. That means if you press down on an element and then move your mouse off the element and release no click event will happen. If you press down outside an element and then move your mouse onto the element and release no click event will happen. CSE

Keyboard events You can register events for keyboards and detect keydown, keypress, and keydown. keydown – fires when the user depresses a key. It repeats while the user keeps the key depressed. keypress – fires when an actual character is being inserted ($, %, ^). Repeats while key is depressed. keyup – fires when the user releases a key CSE

Keyboard events Use the Event property which to determine which key was pressed. which returns a char code value, not a string. Use String.fromCharCode() to convert the which char code into a string.

Keyboard event example document.body.onkeydown = function(e) { console.log("key pressed on body is " + String.fromCharCode(e.which)); } CSE

Mouse Events 1.Mousedown 2.mouseup 3.click 4.dblclick 5.mousemove 6.mouseover 7.mouseout CSE

Dblclick This event is rarely used If you decide to use it, you should never register both a click and dblclick event handler on the same element. Using click and dblclick makes it almost impossible to figure out what the user did. CSE

Mousemove mousemove is a great event, but care must be taken when using it. It takes system time to process all mousemove events, and this event is fired every time you move one pixel. Only registered mousemove when you need it and remove it when you’re done. CSE

Mouseout and Mouseover These events can be confusing Events may fire at unexpected times with confusing values for the target property. My advice is to use jQuery to handle these events. CSE

CSE After adding a mouseover event handler to the div with id=“ev3”, a mouseover event will fire when moving from ev3 to ev4 and then again from ev4 to span.

CSE This happens due to event bubbling, the mouseover event happens on ev4, but ev4 has no mouseover event so it bubbles up to ev3.

Misleading target value In the previous example, the target of the event was ev4. In the next example, the target will be ev4 as well.

CSE Moving from the span element into the ev4 element causes a mouseover event to happen with the target equal to ev4.

How do were determine where the mouse came from? W3C added the relatedTarget property to mouseover and mouseout events. This contains the element the mouse came from in case of mouseover, or the element it goes to in case of mouseout.

Finding the right layer for mouseout and mouseover Event bubbling causes event handlers to be fired at times when you haven’t actually left a layer. CSE

Finding the right layer CSE

Finding the right layer Using the target and relatedTarget properties of an event, you can determine when to correctly handle a mouseout event for a layer. CSE

Finding the right layer example parent.onmouseout = function(e) { if (e.target.id != 'parent') return; var relTarget = e.relatedTarget; while (relTarget != null && relTarget != e.target && relTarget.nodeName != 'BODY') relTarget= relTarget.parentNode if (relTarget== e.target) return; console.log("we have moused out of the parent node element and no other layer, we found the right layer!!!"); } CSE

Other Cool Mouse tricks Figure out which mouse button was clicked: – Use the button property of an mouse event : 0 is the left button 1 is the middle button 2 is the right button CSE

Get mouse coordinate On the mouse event you can use the following properties: 1.clientX – the horizontal coordinate relative to the viewport (browser window). 2.clientY – the vertical coordinate relative to the viewport (browser window). 3.screenX – the horizontal coordinate relative to the origin of the screen (your monitor). 4.screenY – the vertical coordinate relative to the origin of the screen (your monitor) CSE

Your turn! Create event handlers to allow dragging of an element across the screen. Don’t be wasteful and have a handler for mousemove when you don’t need one. CSE

Event References Handling events with javascript QuirksMode DOM Events W3C Capture vs. Bubble Mode CSE