42
DOM Events

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

Embed Size (px)

Citation preview

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

DOM Events

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

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

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

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.

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

CSE 3345 4

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.

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

CSE 3345 5

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.

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

CSE 3345 6

Event ExampleExample 1 <a href="http://www.opera.com/" onclick="alert('Hello')">Say hello</a>

Example 2

<script type="text/javascript">var link = documents.getElementsByTagName(“a”)[0];link.addEventListener(“click”,

function(event) {alert(“Hello”);

}, false);

</script>

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

CSE 3345 7

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.

<a href="http://www.opera.com/" onclick="alert('Hello')">Say hello</a>

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

CSE 3345 8

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

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

CSE 3345 9

Next step in event evolution

• Apply events in blocks of javascript code.

• Code can now be cached and is reusable.

<script type="text/javascript"> document.getElementById("my-link").onclick = waveToAudience; function waveToAudience() { alert("Waving like I've never waved before!"); }</script>

<a id="my-link" href="http://www.opera.com/">My link</a>

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

CSE 3345 10

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

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

CSE 3345 11

Later step in event evolution

• Introduced in DOM 2 Event spec

• Created addEventListener() and removeEventListener()

• Allows developers to register and remove listeners on elements

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

CSE 3345 12

addEventListeners()

Has three parameters 1. type 2. listener 3. useCapture

document.body.addEvent(type, listener, useCapture);

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

CSE 3345 13

addEventListener() example

document.body.addEventListener('click', function (event) {

console.log("hello");},

false);

document.body.addEventListener('click', function(event) { console.log("world");}, false);

type

listener

useCapture

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

CSE 3345 14

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.

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

CSE 3345 15

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

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

CSE 3345 16

removeEventListener() exampleHas 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.

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

CSE 3345 17

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.

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

CSE 3345 18

Window load event example<script type="text/javascript"> 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);</script>

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

CSE 3345 19

Getting information from an event

• The Event interface provides basic contextual information about an event to all registered event handlers.

• Supply a parameter to your event handler or use the arguments method to access the Event interface.

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

CSE 3345 20

Getting information from an event

function clickHandler(event) {if (event !== undefined) {

console.log(event.timeStamp); //1348409181352

console.log(event.type); //clickconsole.log(event.target); //<html

element>}

}document.body.addEventListener('click', clickHandler, false);

Event interface

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

CSE 3345 21

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;

};

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

CSE 3345 22

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.

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

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

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

CSE 3345 24

W3C Event Model

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

CSE 3345 25

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.

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

CSE 3345 26

Event Order Demo

• http://jsfiddle.net/blinkmacalahan/jLb6d/5/

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

CSE 3345 27

Default Events Handler

• Some elements have default event handlers:– <a> navigates to specified href/anchor– <input type=“submit”> submits a form for you– <labels> give focus to the corresponding input

element

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

CSE 3345 28

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.

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

CSE 3345 29

How to stop the default action

Using the Event interface object, call the preventDefault() method.

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

CSE 3345 30

Stop the linkvar 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(); };}

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

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

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

CSE 3345 32

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.

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

CSE 3345 33

Keyboard events

• You can register events for keyboards and detect keydown, keypress, and keyup.

• 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

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

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.

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

CSE 3345 35

Keyboard event exampledocument.body.onkeydown = function(e) {

console.log("key pressed on body is " + String.fromCharCode(e.which));

}

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

CSE 3345 36

Mouse Events

1. mousedown2. mouseup 3. click4. dblclick5. mousemove6. mouseover7. mouseout

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

CSE 3345 37

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.

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

CSE 3345 38

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.

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

CSE 3345 39

mouseout and mouseover

• These events can be confusing

• Events may fire at unexpected times with confusing values for the target property.

• Use jQuery to handle these events.

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

CSE 3345 40

Other Cool Mouse tricks

• Figure out which mouse button was clicked:– Use the button property of a mouse event:• 0 is the left button• 1 is the middle button• 2 is the right button

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

CSE 3345 41

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)