CH 13-1
CH 13-1
JavaScript Group
Department of Information Technology Supporting and Maintenance
Reference Book
• Section 1 • Section 4
What is JavaScript? Document Object Model(DOM) and
JavaScript in HTML DOM Extensions
• Section 5
Variables, Scope, and Memory
Events, Forms and Canvas
• Section 2 • Section 6
Language Basics Client-side Storage
Reference Types
• Section 3
Understanding Objects
Window Object
Outlines
• Events
• Event Flow
• Event Handlers
Events
• Events that occur when a user or browser handles a page are called events.
• When the page loads, it is called an event.
• When the user clicks a button, that click too is an event.
• Other examples include events like pressing any key, closing a window, resizing a
window, etc.
DOM Event Flow
• Event flow describes the order in which events are received on the page.
<body>
<h1>Bubbling and Capturing phase</h1>
<div>
<button class="child">click me</button>
</div>
<script>
var parent = document.querySelector("div");
var child = document.querySelector(".child");
parent.addEventListener("click",function () {
alert("clicked parent");
});
child.addEventListener("click", function () {
alert("clicked child");
});
</script>
</body>
Event Capturing
• In capturing, The outermost element’s event is handled first and then the inner:
1. Document
2. <html>
3. <body>
4. <div>
Event Capturing
<body>
<h1>Bubbling and Capturing phase</h1>
<div>
<button class="child">click me</button>
</div>
<script>
var parent = document.querySelector("div");
var child = document.querySelector(".child");
parent.addEventListener("click",function () {
alert("clicked parent");
},true);
child.addEventListener("click", function () {
alert("clicked child");
});
</script>
</body>
Event Handlers
• Events are certain actions performed either by the user or by the browser itself.
• Events have names like click, load, and mouseover.
• A function that is called in response to an event is called an event handler (or an event
listener)
• Event handlers have names beginning with “on”.
• Assigning event handlers can be accomplished in a number of different ways.
HTML Event Handlers
• Element can be assigned using an HTML attribute with the name of the event handler.
• The value of the attribute should be some JavaScript code to execute.
• For example,
<input type=“button” value=“Click Me” onclick=“alert(‘Clicked’)” />
DOM Level 0 Event Handlers
Example:
<body>
<button id=“myBtn”>Welcome</button>
<script>
document.getElementById(“myBtn”).addEventListener(“click”, function(){
alert(“Welcome to JavaScript”);
}, false);
</script>
</body>
removeEventListener()
Thank you!