0% found this document useful (0 votes)
45 views

ITEW2 WEEK 11 Document Object Model Part 1

The document discusses the Document Object Model (DOM) which represents HTML documents as objects that can be manipulated with JavaScript. It describes how the DOM represents an HTML document as a tree of objects and nodes, and how JavaScript can be used to change HTML elements, attributes, styles, and events. The document also provides examples of DOM methods like getElementById and properties like innerHTML, innerText, and value.

Uploaded by

MOON CAKE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

ITEW2 WEEK 11 Document Object Model Part 1

The document discusses the Document Object Model (DOM) which represents HTML documents as objects that can be manipulated with JavaScript. It describes how the DOM represents an HTML document as a tree of objects and nodes, and how JavaScript can be used to change HTML elements, attributes, styles, and events. The document also provides examples of DOM methods like getElementById and properties like innerHTML, innerText, and value.

Uploaded by

MOON CAKE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

PAMANTASAN NG CABUYAO

COLLEGE OF COMPUTING AND ENGINEERING

COURSE CODE: ITEW2


COURSE DESCRIPTION: CLIENT SIDE SCRIPTING

COURSE INTENDED 1. Design and implement JavaScript codes appropriate to the requirements of the
LEARNING OUTCOMES: programming problem.
2. Write readable JavaScript programs compliant to widely-accepted coding
conventions implementing OOP approach.
3. Create JavaScript programs applying JQuery and Web Storage.

LEARNING MATERIAL
FOR WEEK NUMBER:
11
I. TITLE: DOCUMENT OBJECT MODEL PART 1

II. OBJECTIVES: After this lesson, you are expected to:

1. change the content of HTML elements;


2. change the style (CSS) of HTML elements;
2. implement Event Listener to react to HTML DOM Events.

III. INTRODUCTION: The Document Object Model (DOM) is the data representation of the objects that
comprise the structure and content of a document on the web. In this guide, we'll
briefly introduce the DOM. We'll look at how the DOM represents an HTML or XML
document in memory and how you use APIs to create web content and applications.

The Document Object Model (DOM) is a programming interface for HTML and XML
documents. It represents the page so that programs can change the document
structure, style, and content. The DOM represents the document as nodes and
objects. That way, programming languages can connect to the page.

A Web page is a document. This document can be either displayed in the browser
window or as the HTML source. But it is the same document in both cases. The
Document Object Model (DOM) represents that same document so it can be
manipulated. The DOM is an object-oriented representation of the web page, which
can be modified with a scripting language such as JavaScript.

The W3C DOM and WHATWG DOM standards are implemented in most modern
browsers. Many browsers extend the standard, so care must be exercised when using
them on the web where documents may be accessed by various browsers with
different DOMs [1].

IV. CONTENTS:

Lesson Coverage:

1. DOM Intro
2. DOM Methods
3. DOM Document
4. DOM Elements
5. DOM HTML
6. DOM CSS
7. DOM Animations
8. DOM Events
9. DOM Event Listener

LECTURE NOTES COMPILATION Page 1 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM Intro

When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is
constructed as a tree of Objects:

The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

• JavaScript can change all the HTML elements in the page


• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents.

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and
scripts to dynamically access and update the content, structure, and style of a document."

The W3C DOM standard is separated into 3 different parts:

• Core DOM - standard model for all document types


• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:

• The HTML elements as objects


• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

LECTURE NOTES COMPILATION Page 2 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements [2].

LECTURE NOTES COMPILATION Page 3 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM Methods

• HTML DOM methods are actions you can perform (on HTML Elements).
• HTML DOM properties are values (of HTML Elements) that you can set or change.

The DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML
elements are defined as objects. The programming interface is the properties and methods of each object.

• A property is a value that you can get or set (like changing the content of an HTML element).
• A method is an action you can do (like add or deleting an HTML element).

Example

The following example changes the content (the innerHTML) of the <p> element with id="demo":

<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>

In the example above, getElementById() is a method, while innerHTML is a property.

The getElementById Method

The most common way to access an HTML element is to use the id of the element. In the example above
the getElementById method used id="demo" to find the element.

The innerHTML Property

• The easiest way to get the content of an element is by using the innerHTML property.
• The innerHTML property is useful for getting or replacing the content of HTML elements.
• The innerHTML property can be used to get or change any HTML element, including <html> and <body>.

Example

This example demonstrates the change in a <p> tag content upon clicking a button:

<html>
<body>
<p id="demo"> Hi everyone! </p>
<button onclick = “changeText()”> Change </button>

<script>
function changeText(){
document.getElementById("demo").innerHTML = "Hello World!";
}
</script>

</body>

LECTURE NOTES COMPILATION Page 4 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

</html>

The innerText Property

• The innerText property sets or returns the text content of the specified node, and all its descendants.
• If you set the innerText property, any child nodes are removed and replaced by a single Text node containing
the specified string.

Note: This property is similar to the textContent property, however there are some differences:

• textContent returns the text content of all elements, while innerText returns the content of all elements,
except for <script> and <style> elements.

• innerText will not return the text of elements that are hidden with CSS (textContent will).

Tip: To set or return the HTML content of an element, use the innerHTML property.

Example

This example demonstrates some of the differences between innerText, innerHTML and textContent:

<p id="demo">
This element has extra spacing and contains <span> a span element </span>.
</p>

<script>
function getInnerText() {
alert(document.getElementById("demo").innerText)
}

function getHTML() {
alert(document.getElementById("demo").innerHTML)
}

function getTextContent() {
alert(document.getElementById("demo").textContent)
}
</script>

Get the content of the <p> element above with the specified properties:

innerText returns: "This element has extra spacing and contains a span element."
innerHTML returns: " This element has extra spacing and contains <span>a span element</span>."
textContent returns: " This element has extra spacing and contains a span element."

The innerText property returns just the text, without spacing and inner element tags.
The innerHTML property returns the text, including all spacing and inner element tags.
The textContent property returns the text with spacing, but without inner element tags.

Input Text value Property

• The value property sets or returns the value of the value attribute of a text field.
• The value property contains the default value OR the value a user types in (or a value set by a script) [3].

LECTURE NOTES COMPILATION Page 5 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

Example 1

Change the value of a text field with id = “myText”:

document.getElementById("myText").value = "Johnny Bravo";

Example 2

<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20"
name="fname"><br>

Age (from 1 to 100): <input type="text" id="age" size="20"


name="age"><br>

E-mail: <input type="text" id="email" size="20" name="mail"><br><br>

<input type="submit" value="Submit">


</form>

<script>
function myFunction() {
let at = document.getElementById("email").value.indexOf("@");
let age = document.getElementById("age").value;
let fname = document.getElementById("fname").value;
let submitOK = "true";

if (fname.length > 10) {


alert("The name may have no more than 10 characters");
submitOK = "false";
}

if (isNaN(age) || age < 1 || age > 100) {


alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}

if (submitOK == "false") {
return false;
}
}
</script>
</body>
</html>

LECTURE NOTES COMPILATION Page 6 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

LECTURE NOTES COMPILATION Page 7 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM Document

The HTML DOM document object is the owner of all other objects in your web page.

The HTML DOM Document Object

The document object represents your web page.

If you want to access any element in an HTML page, you always start with accessing the document object.

Below are some examples of how you can use the document object to access and manipulate HTML.

Finding HTML Elements

Changing HTML Elements

Adding and Deleting Elements

Adding Event Handlers

Finding HTML Objects

The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid
in HTML5.

LECTURE NOTES COMPILATION Page 8 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

Later, in HTML DOM Level 3, more objects, collections, and properties were added [4].

LECTURE NOTES COMPILATION Page 9 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM Elements

This lesson teaches you how to find and access HTML elements in an HTML page.

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are several ways to do this:

• Finding HTML elements by id


• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
• Finding HTML elements by HTML object collections

Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id.

This example finds the element with id="intro":

<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements by Id</h2>

<p id="intro">Hello World!</p>


<p>This example demonstrates the <b>getElementsById</b> method.</p>

<p id="demo"></p>

<script>
let myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script>

</body>
</html>

If the element is found, the method will return the element as an object (in myElement).

If the element is not found, myElement will contain null.

Finding HTML Elements by Tag Name

This example finds all <p> elements:

<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements by Tag Name</h2>

LECTURE NOTES COMPILATION Page 10 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

<p>Hello World!</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>

<p id="demo"></p>

<script>
let x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
'The text in first paragraph (index 0) is: ' + x[0].innerHTML;
</script>
</body>
</html>

This example finds the element with id="main", and then finds all <p> elements inside "main":

<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements by Tag Name</h2>

<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
</div>

<p id="demo"></p>

<script>
let x = document.getElementById("main");
let y = x.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) inside "main" is: ' + y[0].innerHTML;
</script>
</body>
</html>

Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name, use getElementsByClassName().
This example returns a list of all elements with class="intro".

<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements by Class Name</h2>

<p>Hello World!</p>

<p class="intro">The DOM is very useful.</p>


<p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>

<p id="demo"></p>
<script>
let x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =

LECTURE NOTES COMPILATION Page 11 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;


<script>
</body>
</html>

Finding elements by class name does not work in Internet Explorer 8 and earlier versions.

Finding HTML Elements by CSS Selectors

If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values
of attributes, etc), use the querySelectorAll() method.

This example returns a list of all <p> elements with class="intro".

<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements by Query Selector</h2>

<p>Hello World!</p>

<p class="intro">The DOM is very useful.</p>


<p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p>

<p id="demo"></p>

<script>
let x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>
</body>
</html>

The querySelectorAll() method does not work in Internet Explorer 8 and earlier versions.

Finding HTML Elements by HTML Object Collections

This example finds the form element with id="frm1", in the forms collection, and displays all element values [5]:

<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements Using document.forms</h2>

<form id="frm1" action="/action_page.php">


First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<input type="submit" value="Submit">
</form>
<p>Click "Try it" to display the value of each element in the form.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

LECTURE NOTES COMPILATION Page 12 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

<script>
function myFunction() {
let x = document.forms["frm1"];
let text = "";
let i;

for (i = 0; i < x.length ;i++) {


text += x.elements[i].value + "<br>";
}

document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

LECTURE NOTES COMPILATION Page 13 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM HTML

The HTML DOM allows JavaScript to change the content of HTML elements.

Changing the HTML Output Stream

JavaScript can create dynamic HTML content:

Date: Thu Apr 29 2021 13:40:03 GMT+0800 (China Standard Time)

In JavaScript, document.write() can be used to write directly to the HTML output stream:

<!DOCTYPE html>
<html>
<body>

<script>
document.write(Date());
</script>

</body>
</html>

Never use document.write() after the document is loaded. It will overwrite the document.

Changing HTML Content

The easiest way to modify the content of an HTML element is by using the innerHTML property.

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML;

This example changes the content of a <p> element:

<!DOCTYPE html>
<html>
body>

<h2>JavaScript can Change HTML</h2>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

Example explained:

• The HTML document above contains a <p> element with id="p1"


• We use the HTML DOM to get the element with id="p1"
• A JavaScript changes the content (innerHTML) of that element to "New text!"

LECTURE NOTES COMPILATION Page 14 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

• This example changes the content of an <h1> element:

<!DOCTYPE html>
<html>
<body>

h1 id="id01">Old Heading</h1>

<script>
let element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>

<p>JavaScript changed "Old Heading" to "New Heading".</p>

</body>
</html>

Example explained:

• The HTML document above contains an <h1> element with id="id01"


• We use the HTML DOM to get the element with id="id01"
• A JavaScript changes the content (innerHTML) of that element to "New Heading"

Changing the Value of an Attribute

To change the value of an HTML attribute, use this syntax:

document.getElementById(id).attribute = new value;

This example changes the value of the src attribute of an <img> element:

<!DOCTYPE html>
<html>
<body>

<img id="image" src="smiley.gif" width="160" height="120">

<script>
document.getElementById("image").src = "landscape.jpg";
script>

<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>

</body>
</html>

Example explained:

• The HTML document above contains an <img> element with id="myImage"


• We use the HTML DOM to get the element with id="myImage"
• A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg" [6]

LECTURE NOTES COMPILATION Page 15 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

LECTURE NOTES COMPILATION Page 16 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM CSS

The HTML DOM allows JavaScript to change the style of HTML elements.

Changing HTML Style

To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style;

The following example changes the style of a <p> element:

<!DOCTYPE html>
<html>
<body>

<p id="p1">Hello World!</p>


<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
</script>

<p>The paragraph above was changed by a script.</p>


</body>
</html>

Using Events

The HTML DOM allows you to execute code when an event occurs.

Events are generated by the browser when "things happen" to HTML elements:

• An element is clicked on
• The page has loaded
• Input fields are changed

You will learn more about events in the next topic.

This example changes the style of the HTML element with id="id1", when the user clicks a button [7]:

Example 1

<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My Heading 1</h1>

<button type="button" onclick="document.getElementById('id1').style.color = 'red'">


Click Me!</button>
body>
</html>

LECTURE NOTES COMPILATION Page 17 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

Example 2

<!DOCTYPE html>
<html>
<body>

<p id="p1">
This is a text.
This is a text.
This is a text.
This is a text.
</p>

<input type="button" value="Hide text" onclick="document.getElementById('p1').style.visibility='hidden'">


<input type="button" value="Show text"
onclick="document.getElementById('p1').style.visibility='visible'">

</body>
</html>

LECTURE NOTES COMPILATION Page 18 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM Animations

Learn to create HTML animations using JavaScript.

A Basic Web Page

To demonstrate how to create HTML animations with JavaScript, we will use a simple web page:

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript Animation</h1>

<div id="animation">My animation will go here</div>

</body>
</html>

Create an Animation Container

All animations should be relative to a container element.

<div id ="container">
<div id ="animate">My animation will go here</div>
</div>

Style the Elements

The container element should be created with style = "position: relative".

The animation element should be created with style = "position: absolute".

#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}

#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}

LECTURE NOTES COMPILATION Page 19 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

<!Doctype html>
<html>
<style>

#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}

#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}

</style>

<body>

<h2>My First JavaScript Animation</h2>

<div id="container">
<div id="animate"></div>
</div>
<body>
</html>

Animation Code

JavaScript animations are done by programming gradual changes in an element's style.

The changes are called by a timer. When the timer interval is small, the animation looks continuous [8].

The basic code is:

let id = setInterval(frame, 5);

function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}

LECTURE NOTES COMPILATION Page 20 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

Create the Full Animation Using JavaScript

<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}

#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>

p><button onclick="myMove()">Click Me</button></p>

<div id ="container">
<div id ="animate"></div>
<div>

<script>
let id = null;

function myMove() {
let elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);

function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>

LECTURE NOTES COMPILATION Page 21 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM Events

HTML DOM allows JavaScript to react to HTML events:

Upon loading the page

Upon mouseover in the first red box

Upon mouse click in the second red box

Reacting to Events

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.

To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:

onclick=JavaScript

Examples of HTML events:

• When a user clicks the mouse


• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key

In this example, the content of the <h1> element is changed when a user clicks on it:

<!DOCTYPE html>
<html>
body>

<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>

</body>
</html>

LECTURE NOTES COMPILATION Page 22 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

In this example, a function is called from the event handler:

<!DOCTYPE html>
<html>
<body>

<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>

HTML Event Attributes

To assign events to HTML elements you can use event attributes.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>
</body>
</html>

In the example above, a function named displayDate will be executed when the button is clicked.

Assign Events Using the HTML DOM

The HTML DOM allows you to assign events to HTML elements using JavaScript:

<!DOCTYPE html>
<html>
<body>

<p>Click "Try it" to execute the displayDate() function.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

LECTURE NOTES COMPILATION Page 23 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

<script>
document.getElementById("myBtn").onclick = displayDate;

function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>

In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn".
The function will be executed when the button is clicked.

The onload and onunload Events

The onload and onunload events are triggered when the user enters or leaves the page.

The onload event can be used to check the visitor's browser type and browser version, and load the proper version
of the web page based on the information.

The onload and onunload events can be used to deal with cookies.

<!DOCTYPE html>
<html>
<body onload="checkCookies()">

<p id="demo"></p>

<script>

function checkCookies() {
let text = "";

if (navigator.cookieEnabled == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

The onchange Event

The onchange event is often used in combination with validation of input fields.

Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the
content of an input field.

<!DOCTYPE html>
<html>
<head>
<script>

LECTURE NOTES COMPILATION Page 24 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

function myFunction() {
let x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onchange="myFunction()">

<p>When you leave the input field, a function is triggered which transforms the input text to upper
case.</p>
</body>
</html>

The onmouseover and onmouseout Events

The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of,
an HTML element:

<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>

<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}

function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
script>
</body>
</html>

The onmousedown, onmouseup and onclick Events

The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is
clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is
triggered, finally, when the mouse-click is completed, the onclick event is triggered [9].

<!DOCTYPE html>
<html>
<body>

<div onmousedown="mDown(this)" onmouseup="mUp(this)"


style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>

<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";

LECTURE NOTES COMPILATION Page 25 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>

LECTURE NOTES COMPILATION Page 26 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

DOM Event Listener

The addEventListener() method

Add an event listener that fires when a user clicks a button:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to attach a click event to a button.</p>

button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>

The addEventListener() method attaches an event handler to the specified element.

The addEventListener() method attaches an event handler to an element without overwriting existing event
handlers.

You can add many event handlers to one element.

You can add many event handlers of the same type to one element, i.e two "click" events.

You can add event listeners to any DOM object not only HTML elements. i.e the window object.

The addEventListener() method makes it easier to control how the event reacts to bubbling.

When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better
readability and allows you to add event listeners even when you do not control the HTML markup.

You can easily remove an event listener by using the removeEventListener() method.

Syntax

element.addEventListener(event, function, useCapture);

The first parameter is the type of the event (like "click" or "mousedown" or any other HTML DOM Event.)

The second parameter is the function we want to call when the event occurs.

The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter
is optional.

LECTURE NOTES COMPILATION Page 27 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

Note that you don't use the "on" prefix for the event; use "click" instead of "onclick".

Add an Event Handler to an Element

Alert "Hello World!" when the user clicks on an element:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to attach a click event to a button.</p>

<button id="myBtn">Try it</button>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Hello World!");
});
</script>
</body>
</html>

You can also refer to an external "named" function:

Alert "Hello World!" when the user clicks on an element:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to execute a function when a user clicks on a
button.</p>

<button id="myBtn">Try it</button>

<script>
document.getElementById("myBtn").addEventListener("click", myFunction);

function myFunction() {
alert ("Hello World!");
}
</script>
</body>
</html>

Add Many Event Handlers to the Same Element

The addEventListener() method allows you to add many events to the same element, without overwriting existing
events:

<!DOCTYPE html>
<html>
body>

<h2>JavaScript addEventListener()</h2>

LECTURE NOTES COMPILATION Page 28 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

<p>This example uses the addEventListener() method to add two click events to the same
button.</p>

<button id="myBtn">Try it</button>

<script>
let x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);

function myFunction() {
alert ("Hello World!");
}

function someOtherFunction() {
alert ("This function was also executed!");
}
<script>
</body>
</html>

You can add events of different types to the same element:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to add many events on the same button.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
let x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);

function myFunction() {
document.getElementById("demo").innerHTML += "Moused over!<br>";
}

function mySecondFunction() {
document.getElementById("demo").innerHTML += "Clicked!<br>";
}

function myThirdFunction() {
document.getElementById("demo").innerHTML += "Moused out!<br>";
}
</script>
</body>
</html>

Add an Event Handler to the window Object

LECTURE NOTES COMPILATION Page 29 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements,
the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

Add an event listener that fires when a user resizes the window:

<!DOCTYPE html>
<html>
body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method on the window object.</p>

<p>Try resizing this browser window to trigger the "resize" event handler.</p>

<p id="demo"></p>

<script>
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = Math.random();
});
</script>
</body>
</html>

Passing Parameters

When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example demonstrates how to pass parameter values when using the addEventListener()
method.</p>

<p>Click the button to perform a calculation.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
let p1 = 5;
let p2 = 7;

document.getElementById("myBtn").addEventListener("click", function() {
myFunction(p1, p2);
});

function myFunction(a, b) {
let result = a * b;
document.getElementById("demo").innerHTML = result;
}
</script>

LECTURE NOTES COMPILATION Page 30 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

</body>
</html>

Event Bubbling or Event Capturing?

There are two ways of event propagation in the HTML DOM, bubbling and capturing.

Event propagation is a way of defining the element order when an event occurs. If you have a <p> element inside a
<div> element, and the user clicks on the <p> element, which element's "click" event should be handled first?

In bubbling the inner most element's event is handled first and then the outer: the <p> element's click event is
handled first, then the <div> element's click event.

In capturing the outer most element's event is handled first and then the inner: the <div> element's click event will
be handled first, then the <p> element's click event.

With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter:

addEventListener(event, function, useCapture);

The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the
capturing propagation.

<!DOCTYPE html>
<html>
<head>
<style>
#myDiv1, #myDiv2 {
background-color: coral;
padding: 50px;
}

#myP1, #myP2 {
background-color: white;
font-size: 20px;
border: 1px solid;
padding: 20px;
}
</style>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">


head>
<body>

<h2>JavaScript addEventListener()</h2>

<div id="myDiv1">
<h2>Bubbling:</h2>
<p id="myP1">Click me!</p>
</div><br>

<div id="myDiv2">
<h2>Capturing:</h2>
<p id="myP2">Click me!</p>
</div>

<script>

LECTURE NOTES COMPILATION Page 31 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

document.getElementById("myP1").addEventListener("click", function() {
alert("You clicked the white element!");
}, false);

document.getElementById("myDiv1").addEventListener("click", function() {
alert("You clicked the orange element!");
}, false);

document.getElementById("myP2").addEventListener("click", function() {
alert("You clicked the white element!");
}, true);

document.getElementById("myDiv2").addEventListener("click", function() {
alert("You clicked the orange element!");
}, true);
</script>
</body>
</html>

The removeEventListener() method

The removeEventListener() method removes event handlers that have been attached with the addEventListener()
method [10]:

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
font-size: 20px;
}
</style>
</head>
<body>

<h2>JavaScript removeEventListener()</h2>

<div id="myDIV">
<p>This div element has an onmousemove event handler that displays a random number
every time you move your mouse inside this orange field.</p>

<p>Click the button to remove the div's event handler.</p>

<button onclick="removeHandler()" id="myBtn">Remove</button>


</div>

<p id="demo"></p>

<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {
document.getElementById("demo").innerHTML = Math.random();
}

LECTURE NOTES COMPILATION Page 32 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

function removeHandler() {
document.getElementById("myDIV").removeEventListener("mousemove",
myFunction);
}
</script>
</body>
</html>

V. REFERENCES: [1] MDN Web Docs, “Introduction to the DOM”, [Online]. Available:
https://developer.mozilla.org/en-

LECTURE NOTES COMPILATION Page 33 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

US/docs/Web/API/Document_Object_Model/Introduction. [Accessed: 20-Apr-


2021].

[2] W3Schools, “JavaScript HTML DOM”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom.asp. [Accessed: 20-Apr-2021].

[3] W3Schools, “JavaScript - HTML DOM Methods”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom_methods.asp. [Accessed: 20-Apr-
2021].

[4] W3Schools, “JavaScript - HTML DOM Document”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom_document.asp. [Accessed: 20-Apr-
2021].

[5] W3Schools, “JavaScript - HTML DOM Elements”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom_elements.asp. [Accessed: 20-Apr-
2021].

[6] W3Schools, “JavaScript HTML DOM – Changing HTML”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom_html.asp. [Accessed: 20-Apr-2021].

[7] W3Schools, “JavaScript HTML DOM – Changing CSS”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom_css.asp. [Accessed: 20-Apr-2021].

[8] W3Schools, “JavaScript HTML DOM Animation”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom_animate.asp. [Accessed: 20-Apr-
2021].

[9] W3Schools, “JavaScript HTML DOM Events”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom_events.asp. [Accessed: 20-Apr-2021].

[10] W3Schools, “JavaScript HTML DOM EventListener”, [Online]. Available:


https://www.w3schools.com/js/js_htmldom_eventlistener.asp. [Accessed: 20-Apr-
2021].

VI. ASSESSMENT TASK:

Assessment task is posted as scheduled in our MS Team.

DISCLAIMER

Every reasonable effort is made to ensure the accuracy of the information used in the creation of this
reference material, without prejudice to the existing copyrights of the authors. As an off-shoot of the innumerable
difficulties encountered during these trying times, the authors endeavored to ensure proper attribution of the
esteemed original works, by way of footnotes or bibliography, to their best abilities and based on available resources,
despite the limited access and mobility due to quarantine restrictions imposed by the duly constituted authorities.

We make no warranties, guarantees or representations concerning the accuracy or suitability of the


information contained in this material or any references and links provided here. Links to other materials in our
CPOD and CAM was made in good faith, for non-commercial teaching purposes only to the extent justified for the
purpose, and consistent with fair use under Sec. 185 of Republic Act No. 8293, otherwise known as the Intellectual
Property Code of the Philippines.

COPYRIGHT NOTICE

LECTURE NOTES COMPILATION Page 34 of 35


2nd Semester A.Y. 2021-2022
PAMANTASAN NG CABUYAO
COLLEGE OF COMPUTING AND ENGINEERING

Materials contained in the learning packets have been copied and conveyed to you by or on behalf of
Pamantasan ng Cabuyao pursuant to Section IV - The Copyright Act (RA) 8293 of the Intellectual Property Code of
the Philippines.

You are not allowed by the Pamantasan ng Cabuyao to reproduce or convey these materials. The content may
contain works which are protected by copyright under RA 8293. You may be liable to copyright infringement for any
copying and/ or distribution of the content and the copyright owners have the right to take legal action against such
infringement.

Do not remove this notice.

LECTURE NOTES COMPILATION Page 35 of 35


2nd Semester A.Y. 2021-2022

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy