Sie sind auf Seite 1von 80

EVENTS AND EVENT

HANDLERS

HEERAH D, PESU
WHAT IS AN EVENT?
 JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.

 When the page loads, it is called an event. When the user clicks a button, pressing any key,
closing a window, resizing a window, etc are all events.

 Developers can use these events to execute JavaScript coded as responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.

 Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.

HEERAH D, PESU
HEERAH D, PESU
EVENT
 An event is nothing more than a signal. It communicates that
something has just happened.

 To detect the activities between the browser and the user is known
as events and to provide computation when these occurs is specified
through event-driven programming.

 Event-driven programming is the part of program executed at


completely unpredictable moment depending on user interaction
triggers.


HEERAH D, PESU Event is an object that is implicitly created by the browser.
EVENT HANDLER

 An event handler is a script that is executed implicitly in response to an event


occurred.

 Functions of Event Handling


 Event Handling identifies where an event should be forwarded.
 It makes the forward event.
 It receives the forwarded event.
 It takes some kind of appropriate action in response, such as writing to a log,
sending an error or recovery routine or sending a message.
 The event handler may ultimately forward the event to an event consumer.

HEERAH D, PESU
 Events and Events handler are something like Exceptions and
Exception handling where both require some program action when
some event or error occurs.

 Since events are javascript objects, they are case sensitive.


 click is an event but Click is not an event.

 Process of connecting events and event handler is known as


registration.

HEERAH D, PESU
EVENT HANDLERS
 Events apply to HTML tags as follows:

 Focus, Blur, Change events: text fields, textareas, and selections

 Click events: buttons, radio buttons, checkboxes, submit buttons, reset


buttons, links

 Select events: text fields, textareas

 MouseOver event: links

 If an event applies to an HTML tag, then you can define an event handler for it.
In general, an event handler has the name of the event, preceded by "on."

 For example, the event handler for the Focus event is onFocus.
HEERAH D, PESU
EVENTS, ATTRIBUTES AND TAGS
 Events are associated with HTML tag attributes, which can be used to
connect the events to handlers.

 The attributes have names that are closely related to their associated
events.

 Below table shows Attributes, corresponding tags and their description


 (1) the most commonly used attributes related to events,
 (2) tags that can include the attributes, and
 (3) the circumstances under which the associated events are created.
HEERAH D, PESU
HEERAH D, PESU
HEERAH D, PESU
HEERAH D, PESU
HEERAH D, PESU
TWO WAYS OF REGISTERING EVENTS

 Button event (Inline model)


 Example
<input type=“button” id=“mybtn”
onclick=“mybuttonhandler()”>
 Event property on button object (Traditional
model)
 Example
document.getElementById(“mybtn”).oncl
ick=mybuttonhandler;
HEERAH D, PESU
EXAMPLE

HEERAH D, PESU
Events and JavaScript
 To work with events, there are two things
you need to do:

Listen for events


inline model
traditional model
W3C model
React to events
HEERAH D, PESU
Listening for Events
 Sometimes, our application will fire events automatically...such as when it loads.

 Sometimes, our application will fire events as a reaction to us actually interacting


with it.

 The thing to note is that our application is bombarded by events constantly


whether we intended to have them get fired or not.

 Our task is to tell our application to listen only to the events we care about.

 Listening to the right event is handled entirely by a function


called addEventListener.
HEERAH D, PESU
Syntax - source.addEventListener(eventName,
eventHandler, false);
 Source - We call addEventListener via an element or object that we want to listen
for events on. Usually it is the DOM element, but it can also be
our document, window, or any object specially designed to fire events.

 Event Name - The first argument we specify to the addEventListener function is


the name of the event we are interested in listening to. Example : click,
mouseover, mousein, mouseout, dblclick etc.,

 Event Handler - The second argument requires us to specify a function that will
get called when the event gets overheard. This function is known as the event
handler.

 To Capture, or Not to Capture - The last argument is made up of either a true or


a false.
HEERAH D, PESU
For Example -
document.addEventListener("click",
changeColor, false);
 In the above example :

 Document - is the source


 “click” - is the name of the event that we are
interested to listen
 changeColor - is the Event handler function that will be
called once the above event has occurred.
 false - Boolean value specifies the Capture is disabled.
HEERAH D, PESU
HEERAH D, PESU
BEFORE CLICK
EVENT
HEERAH D, PESU
AFTER CLICK
HEERAH D, PESU EVENT
HEERAH D, PESU
RemoveEventListener()
 The EventTarget.removeEventListener() method removes from
the EventTarget an event listener previously registered.

 Syntax:

 element.removeEventListener(event,listener,useCapture)

 Parameters: It accepts three parameters which are specified below-

 event: It is a string which describes the name of event that has to be remove.

 listener: It is the function of the event handler to remove.

 useCapture: It is an optional parameter. By default it is Boolean value false


which specifies the removal of event handler from the bubbling phase and if it
is true than the removeEventListener() method removes the event handler
from the capturing phase.
HEERAH D, PESU
LOAD
 The onload event in JavaScript triggers when a web page
loads in a browser.

 The onload Event is defined in BODY element.

 “page load welcome message example”

HEERAH D, PESU
ONCLICK
 The onclick event in JavaScript simply triggers when you
click a specific control, such as button control.

 “Date Example”

HEERAH D, PESU
MOUSE EVENTS
 The mouse events in JavaScript are those events that triggers
while operating the mouse.

 Three important mouse events are:

 When the mouse cursor enters an element, an onmouseover


event occurs for that element
 When the mouse cursor leaves the element, an onmouseout
event occurs for that element
 onmousemove event fires whenever the user moves the mouse
HEERAH D, PESU
MOUSE EVENTS
 The mouse events in JavaScript are those events that triggers while
operating the mouse.

 click – when the mouse clicks on an element (touchscreen devices


generate it on a tap).

 contextmenu – when the mouse right-clicks on an element.

 mousedown / mouseup – when the mouse button is pressed / released


over an element.

 mousemove – when the mouse is moved.

HEERAH D, PESU
ONMOUSEOVER AND ONMOUSEOUT
 The mouseover event occurs when a mouse pointer comes over an element,
and mouseout – when it leaves.

 A fast mouse move may skip intermediate elements.

 They are all about hovering over something and hovering away from
something.

 ONMOUSEOVER :

This event corresponds to hovering the mouse pointer over the element
and its children, to which it is bound to.

 ONMOUSEOUT :

Whenever the mouse cursor leaves the element which handles a


mouseout event, a function associated with it is executed.
HEERAH D, PESU
MOUSEENTER AND MOUSELEAVE
 The mouseenter and mouseleave events do not bubble. This makes
them unique.

 All four of these events behave identically when there are no child
elements at play. If there are child elements at play :

 mouseover and mouseout will get fired each time you move the
mouse over and around a child element. This means that you could
be seeing many unnecessary event fires even though it seems like
you are moving your mouse within a single region.

 mouseenter and mouseleave will get fired only once. It doesn't


matter how many child elements your mouse moves through.
HEERAH D, PESU
EVENT ORDER
 An action may trigger multiple events.

 For instance,

 a click first triggers mousedown, when the button is pressed,


then mouseup and click when it’s released.

 In cases when aa single action initiates multiple events, their order is


fixed. That is, the handlers are called in the order

mousedown → mouseup → click

HEERAH D, PESU
EVENT ORDER
 Click-related events always have the which property, which allows to get
the exact mouse button.

 It is not used for click and contextmenu events, because the former
happens only on left-click, and the latter – only on right-click.

 But if we track mousedown and mouseup, then we need it, because these
events trigger on any button, so which allows to distinguish between
“right-mousedown” and “left-mousedown”.

 There are the three possible values:

 event.which == 1 – the left button

 event.which == 2 – the middle button

 event.which == 3 – the right button


HEERAH D, PESU
event Object & this
 event object stores information about the event that
called the event-handling function

 In an event-handling function, this refers to the DOM


object on which the event occurred

 this keyword enables one event handler to apply a


change to one of many DOM elements, depending on which
one received the event

HEERAH D, PESU
EventObject & this
 When a event listener’s event occurs and it calls its associated function, it also passes a
single argument to the function—a reference to the event object.

 The event object contains a number of properties that describe the event that occurred.

HEERAH D, PESU
EventObject & this
 By convention, the parameter name e is used in event-triggered functions to receive
the event object argument. If I wanted to determine the type of event that occurred,
such as a click, example:

 function myEvent(e)

var evtType = e.type alert(evtType) // displays click, or whatever the


event type was

 In JavaScript the this keyword always refers to the “owner” of a function. hence
event handlers it is very useful if this refers to the HTML element the event is handled
by, so that you have easy access to it.

 In the W3C model it works the same as in the traditional model , it refers to the HTML
HEERAH D, PESU
element currently handling the event.
EventObject & this

 If you register doSomething() as the click event handler of any HTML element,
that element gets a red background whenever the user clicks on it.

 element.addEventListener('click',doSomething,false);
another_element.addEventListener('click',doSomething,false);

function doSomething()

this.style.backgroundColor = '#cc0000';

}
HEERAH D, PESU
EventObject & this
In JavaScript this always refers to
the “owner” of the function we're
executing, or rather, to the object
that a function is a method of.
The function doSomething() in a
page, its owner is the page, or
rather, the window object (or global
object) of JavaScript.
An onclick property, though, is
owned by the HTML element it
belongs to.
HEERAH D, PESU
EventObject & this

The function is copied in its


entirety to
the onclick property (which
now becomes a method). So
if the event handler is
executed this refers to the
HTML element and
its color is changed.

HEERAH D, PESU
EventObject & this

The use of this is fullest


extent. Each time the function
is called, this refers to the
HTML element that is currently
handling the event, the HTML
element that "owns" the copy
of doSomething().

HEERAH D, PESU
event Object Properties
Property Description

altKey This value is true if the Alt key was pressed when the event fired.
cancelBubble Set to true to prevent the event from bubbling. Defaults to false.
(See Section 14.9, Event Bubbling.)
clientX and clientY The coordinates of the mouse cursor inside the client area (i.e., the
active area where the web page is displayed, excluding scrollbars,
navigation buttons, etc.).
ctrlKey This value is true if the Ctrl key was pressed when the event fired.

keyCode The ASCII code of the key pressed in a keyboard event. See
Appendix D for more information on the ASCII character set.
screenX and screenY The coordinates of the mouse cursor on the screen coordinate system.
shiftKey This value is true if the Shift key was pressed when the event fired.
type The name of the event that fired, without the prefix "on".
HEERAH D, PESU
Keyboard Events
 To work with keyboards in a HTML document, there are three events that you will need
to familiarize yourself with. Those events are:

 keydown
 keypress
 keyup

HEERAH D, PESU
 The keydown event is fired when you press down on a key on your keyboard.

 The keyup event is fired when you release a key that you just pressed. Both of
these events work on any key that you interact with.

 The keypress event is a special bird. At first glance, it seems like this event is
fired when you press down on any key. Keypress event is fired only when you press
down on a key that displays a character (letter, number, etc.).

HEERAH D, PESU
The Keyboard Event Properties
 ctrlKey, altKey, shiftKey
 These three properties return a true if the Ctrl key, Alt key, or Shift key are
pressed.

 metaKey
 The metaKey property is similar to the ctrlKey, altKey, and shiftKey properties
in that it returns a true if the Meta key is pressed.
 The Meta key is the Windows key on Windows keyboards and the Command key
on Apple keyboards

HEERAH D, PESU
The Keyboard Event Properties
 charCode
 The charCode property returns the Unicode character code of the key that
triggered the onkeypress event.
 The Unicode character code is the number of a character (e.g. the number
"97" represents the letter "a").
 Note: If this property is used on onkeydown or onkeyup events, the returned
value is always "0".
 This property is read-only.

 Syntax
 event.charCode

HEERAH D, PESU
The Keyboard Event Properties
 keyCode
 The keyCode property returns the Unicode character code of the key that triggered
the onkeypress event, or the Unicode key code of the key that triggered
the onkeydown or onkeyup event.

 The difference between the two code types:


 Character codes - A number which represents an ASCII character
 Key codes - A number which represents an actual key on the keyboard

HEERAH D, PESU
FORM RELATED EVENTS
 JavaScript is to check the values provided in forms by users to determine whether the values
are sensible.

 Script processes the form data checks for data and carry on the user dialog concerning invalid
input data entirely on the client.

 Detecting incorrect form data on the client produces quicker responses to user which results in
lesser network traffic.

 Validation is crucial if any incorrect data is present, then the database would get corrupted.

 A JavaScript event handler function detects the error, the function should produce an alert
message indicating the error to the user and inform the user of the correct format for the
input.
HEERAH D, PESU
ONSUBMIT, ONRESET, ONFOCUS, ONBLUR
 The onsubmit event in JavaScript is used with FORM element and is triggered when
the form is submitted.

 The onreset event in JavaScript is defined with a form and is triggered when the
fields of form are reset.

 The onblur event occurs when an object loses focus. The onblur event is most
often used with form validation code (e.g. when the user leaves a form field).

 The onfocus event occurs when an element gets focus. The onfocus event is most
often used with <input>, <select>, and <a>.

HEERAH D, PESU

 The onfocus event is the opposite of the onblur event.


Event Propagation
 Event bubbling and capturing are two ways of event propagation in the HTML
DOM API.

 When an event occurs in an element inside another element, and both


elements have registered a handle for that event.

 With bubbling, the event is first captured and handled by the innermost
element and then propagated to outer elements.

 With capturing, the event is first captured by the outermost element and
propagated to the inner elements.

 The term event propagation is often used as a synonym of event bubbling.

HEERAH D, PESU
Event Bubbling

 events ripple and affect a bunch elements that lie in their path

HEERAH D, PESU
Event Bubbling
 The event bubbling is used where a single event, such as a mouse click, may be
handled by two or more event handlers defined at different levels of the Document
Object Model (DOM) hierarchy.

 The event bubbling process starts by executing the event handler defined for individual
elements at the lowest level (e.g. individual hyperlinks, buttons, table cells etc.).

 From there, the event bubbles up to the containing elements (e.g. a table or a form
with its own event handler), then up to even higher-level elements (e.g.
the BODY element of the page).

 Finally, the event ends up being handled at the highest level in the DOM hierarchy,
the document element itself (provided that your document has its own event handler).

HEERAH D, PESU
Event Bubbling

The bubbling guarantees that click on Div 3 will trigger onclick first on the innermost element 3
(also caled the target), then on the element 2, and the last will be element 1.

HEERAH D, PESU
The deepest element which triggered the event is called the target or, the originating
element.

When handlers trigger on parents:


•event.target/srcElement - remains the same originating element.
•this - is the current element, the one event has bubbled to, the one
which runs the handler.

HEERAH D, PESU
<body id="theBody" class="item">
<div id="one_a" class="item">
<div id="two" class="item">
<div id="three_a" class="item">
<button id="buttonOne" class="item">one</button>
</div>
<div id="three_b" class="item">
<button id="buttonTwo" class="item">two</button>
<button id="buttonThree" class="item">three</button>
</div>
</div>
</div>
<div id="one_b" class="item">
HEERAH D, PESU
</div> </body>
HEERAH D, PESU
HEERAH D, PESU
HEERAH D, PESU
HEERAH D, PESU
HEERAH D, PESU
HEERAH D, PESU
EVENT CAPTURING
 However, strictly speaking, event propagation is a wider term: it
includes not only event bubbling but also event capturing.

 Event capturing is the opposite of bubbling (events are handled at


higher levels first, then sink down to individual elements at lower
levels).

 Event capturing is supported in fewer browsers and rarely used;


notably, Internet Explorer prior to version 9.0 does not support event
capturing.

HEERAH D, PESU
JavaScript Timing Events
 With JavaScript, it is possible to execute some code NOT
immediately after a function is called, but after a specified
time interval. This is called timing events.

 It's very easy to time events in JavaScript. The two key methods
that are used are:

 setTimeout() - executes a code some time in the future


 clearTimeout() - cancels the setTimeout()

 Note: The setTimeout() and clearTimeout() are both methods of


the HTML DOM Window object.
HEERAH D, PESU
setTimeout()
 The setTimeout() method returns a value.

 Syntax
var t=setTimeout("javascript statement",milliseconds);

 In the statement above, the value is stored in a variable called t. If you want
to cancel this setTimeout(), you can refer to it using the variable name.

 The first parameter of setTimeout() is a string that contains a JavaScript


statement. This statement could be a statement like "alert('5 seconds!')" or a
call to a function, like "alertMsg()".
 The second parameter indicates how many milliseconds from now you want to
execute the first parameter.
HEERAH D, PESU
clearTimeout()
 Syntax
clearTimeout(setTimeout_variable)

 clearTimeout is used to stop the Infinite loop time that is set.

HEERAH D, PESU
setInterval()
 The setInterval function is similar to setTimeout.

 The setInterval() method calls a function or evaluates an expression at specified


intervals (in milliseconds).

 The setInterval() method will continue calling the function until clearInterval() is
called, or the window is closed.

 The ID value returned by setInterval() is used as the parameter for the


clearInterval() method.

 Syntax : setInterval(function, milliseconds)


HEERAH D, PESU
Synthetic Events
 The first thing is to create your custom event by calling
the CustomEvent constructor:

 “myEventName” is the event name here. The CustomEvent object that wraps
all of that is associated to the myEvent variable.

 The way you fire an event programmatically is by using


the dispatchEvent method:

HEERAH D, PESU
 Further we need to fully complete the circle by using
an addEventListener somewhere in your app that is listening for this event:

 Care should be taken that addEventListener code runs before you actually
dispatch the event.

 Otherwise, you'll find that your event will fire before your event listener is
even ready.

HEERAH D, PESU
What are Cookies ?
 A cookie (called an Internet or Web cookie) is the term given to describe a type
of message that is given to a web browser by a web server.

 The main purpose of a cookie is to identify users and possibly prepare


customized Web pages or to save site login information for you.

 When you enter a website using cookies, you may be asked to fill out a form
providing personal information; like your name, email address, and interests.

 This information is packaged into a cookie and sent to your Web browser, which
then stores the information for later use.

HEERAH D, PESU
Cookies
 The next time you go to the same Web site, your browser will send the cookie
to the Web server. The message is sent back to the server each time the
browser requests a page from the server.

 A web server has no memory so the hosted website you are visiting transfers a
cookie file of the browser on your computer's hard disk so that the site can
remember who you are and your preferences.

 This message exchange allows the Web server to use this information to
present you with customized Web pages.

 So, for example, instead of seeing just a generic welcome page you might see
a welcome page with your name on it.
HEERAH D, PESU
 When a browser requests a web page from a server, cookies belonging to the
page are added to the request. This way the server gets the necessary data to
"remember" information about users.

 JavaScript can create, read, and delete cookies with


the document.cookie property.

 Create a Cookie:
 document.cookie = "username=Daniel";

HEERAH D, PESU
 You can also add an expiry date (in UTC time). By default, the cookie is
deleted when the browser is closed:
 document.cookie = "username=Daniel; expires=Thu, 18 Dec 2013 12:00:00 UTC";

 Read a Cookie:
 var x = document.cookie;

 Delete a Cookie:
 You don't have to specify a cookie value when you delete a cookie. Just set the
expires parameter to a passed date.

HEERAH D, PESU
 The document.cookie property looks like a normal text string. But it is
not.

 Even if you write a whole cookie string to document.cookie, when you


read it out again, you can only see the name-value pair of it.

 If you set a new cookie, older cookies are not overwritten.

 The new cookie is added to document.cookie, so if you read


document.cookie again you will get something like:

 cookie1 = value; cookie2 = value;

HEERAH D, PESU
 Storing of data locally in native client applications - registry, ini files, xml
files etc.

 Limited facility in Browsers with the use of cookies.

 Problems with cookies:


 Included with every request that goes across to the server
 Very limited size – around 4KB usually.
 Not encrypted unless the whole application is over SSL.
 More network traffic, slowing down the app.

HEERAH D, PESU
We need….
 More storage space locally.
 Data must persist.
 Should not transmit to the server unnecessarily. The solution is……HTML5
LocalStorage.

HEERAH D, PESU
LocalStorage Property
 LocalStorage is a type of web storage that allows Javascript websites and
apps to store and access data right in the browser with no expiration date.

 This means the data stored in the browser will persist even after the browser
window has been closed.

 The localStorage property allow to save key/value pairs in a web browser.

 localStorage is similar to sessionStorage, except that while data stored


in localStorage has no expiration time, data stored in sessionStorage gets
cleared when the page session ends — that is, when the page is closed.

HEERAH D, PESU
To use localStorage in your web applications, there are five methods to choose
from:

 setItem(): Add key and value to localStorage


 getItem(): Retrieve a value by the key from localStorage
 removeItem(): Remove an item by key from localStorage
 clear(): Clear all localStorage
 key(): Passed a number to retrieve nth key of a localStorage

HEERAH D, PESU
setItem()
 This method just as the name implies allows you to store values in the
localStorage object.

 It takes two parameters, a key and a value. The key can be referenced later
to fetch the value attached to it.

window.localStorage.setItem('name', 'Obaseki Nosa’);

 Where name is the key and Obaseki Nosa is the value. Also note that localStorage can
only store strings.

HEERAH D, PESU
getItem()
 The getItem() method allows you to access the data stored in the browser’s
localStorage object.

 It accepts only one parameter which is the key and returns the value as a
string.

 To retrieve the user key stored above:


window.localStorage.getItem('user');

 This returns a string with value as;


“{“name”:”Obaseki Nosa”,”location”:”Lagos”}”

HEERAH D, PESU
removeItem()
 The removeItem() method when passed a key name, will remove that key
from the storage if it exists. If there is no item associated with the given key,
this method will do nothing.

window.localStorage.removeItem('name');

HEERAH D, PESU
clear()
 This method, when invoked clears the entire storage of all records for that
domain. It does not receive any parameters.

window.localStorage.clear();

HEERAH D, PESU
key()
 The key() method comes in handy in situations where you need to loop
through keys and allows you pass a number or index to local storage to
retrieve the name of the key.

var KeyName = window.localStorage.key(index);

HEERAH D, PESU
LocalStorage JavaScript limitations
As easy as it is to use localStorage, it is also easy to misuse it. The following are
limitations and also ways to NOT use localStorage:

 Do not store sensitive user information in localStorage


 It is not a substitute for a server based database as information is only stored
on the browser
 LocalStorage is limited to 5MB across all major browsers
 LocalStorage is quite insecure as it has no form of data protection and can be
accessed by any code on your web page
 LocalStorage is synchronous. Meaning each operation called would only
execute one after the other

HEERAH D, PESU

Das könnte Ihnen auch gefallen