0% found this document useful (0 votes)
11 views34 pages

Unit 5 DOM and DOM Event handling

The document provides an overview of client-side JavaScript, focusing on the Document Object Model (DOM) and event handling. It explains the structure and manipulation of HTML documents through JavaScript, detailing various DOM levels, categories, and methods for accessing HTML elements. Additionally, it covers event handling techniques and models used in JavaScript to enhance interactivity on web pages.

Uploaded by

khushi.shelote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views34 pages

Unit 5 DOM and DOM Event handling

The document provides an overview of client-side JavaScript, focusing on the Document Object Model (DOM) and event handling. It explains the structure and manipulation of HTML documents through JavaScript, detailing various DOM levels, categories, and methods for accessing HTML elements. Additionally, it covers event handling techniques and models used in JavaScript to enhance interactivity on web pages.

Uploaded by

khushi.shelote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit 5

Fundamental Client-Side JavaScript and


Event
Handling
By

Mrs. Sanjyot Thuse

Assistant Professor

Department of E & TC

PES Modern College of Engineering


Contents

 JavaScript Object Models: Object Model Overview, The Initial JavaScript


Object Model, The Object Models
 The Standard Document Object Model: DOM Flavors, Document Trees,
Accessing Elements,
 Creating Nodes, Inserting and Appending Nodes, Deleting and Replacing
Nodes, The DOM and
 HTML Elements, The DOM and CSS, The DOM Versus DHTML Object
Models. Overview of Events
 and Event Handling, The Basic Event Model, Netscape 4 Event Model,
Internet Explorer 4+ Event
 Model, DOM2 Event Model, Event Model Issues.
Object Model
 Object Models show how objects perform real-world tasks.

 These models are required to add dynamic functionality to an HTML page.

 In client-side JavaScript, an object model is the interface to the various aspects of the
browser and the document that can be manipulated in code.

 Over time the object models supported in browsers have evolved, but for simplicity, we
may break down object models by browser type and version.

 We also note that object models may focus on accessing the features and characteristics
of a

browser—a Browser Object Model (BOM)

document contained in a browser—the Document Object Model (DOM)


Browser based JavaScript object model

 There are primary four components of this model.


1. The core JavaScript language (for example, data types,
operators, and statements)
2. The core objects primarily related to data types (for
example, Date, String, and Math)
3. The browser objects (for example, Window, Navigator,
andLocation)
4. The document objects (for example, Document, Form,
and Image)
Document Object Model

When we write statement


alert(“Hello JavaScript”)
We are actually invoking window object.

When we write
document.write() or
Document.getElementById()
We are invoking document objects
HTML page Window
<!DOCTYPE html>
<html>
<head> Hello </head> Document
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p> HTML
<script>
let text = "";
let i = 0; head body
while (i < 10)
{
text += "<br>The number is " + i;
h2 p scrip
i++;
}

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

</body>
</html>
Why DOM??
 HTML is used to structure the webpage and JS is used to add behaviour to the webpage.
 The moment you load the HTML file into browser;
 JS does not understand the HTML document. It does not understand the tags.
 Thus, a corresponding document (DOM) is created.
 DOM is basically the representation of the same HTML document but in a different format
with the use of objects.
 Javascript interprets DOM easily i.e javascript can not understand the tags(<h1>H</h1>) in
HTML document but can understand object h1 in DOM. Now, Javascript can access each of
the objects (h1, p, etc) by using different functions.
 Using DOM, programmers can build, construct, add, modify, delete, or navigate elements or
contents. Everything present on an HTML webpage can be edited using DOM.
 DOM is not a programming language but it the way you access or modify data. DOM is a
logical structure of a JS program.
DOM Structure:
 DOM can be thought of as a Tree or Forest(more than one tree).
 Tree will have nodes, Children, siblings, leaf nodes etc
DOM Flavors
Four levels of the DOM are defined as follows
 DOM Level 0 Roughly equivalent to what Netscape 3.0 and Internet Explorer 3.0 supported.
We call this DOM the classic, or traditional, JavaScript object model. This form of the DOM
was presented in slide no 5 and supports the common document object
collections—forms[], images[], anchors[], links[], and applets[].
 DOM Level 1 Provides the ability to manipulate all elements in a document through a common
set of functions. In DOM Level 1, all elements are exposed, and parts of the page can be read
and written to at all times. The Level 1 DOM provides capabilities similar to Internet
Explorer’s, except that it is cross-browser–compatible and standardized.
 DOM Level 2 Provides further access to page elements primarily related to CSS and focuses
on combining DOM Levels 0 and 1 while adding improved support for working with XML
documents. This form of the DOM also adds an advanced event model and the lesser-known
extensions such as traversal and range operations.
 DOM Level 3 Made some modifications to the core facilities provided by DOM Levels 1 and 2,
and introduced a number of sparsely implemented features such as XML Load and Save.
Some of the more practical parts of DOM Level 3 live on in the HTML5 specification.
DOM Categories
There are five categories in DOM
 DOM Core Specifies a generic model for viewing and manipulating a marked up
document as a tree structure.
 DOM HTML Specifies an extension to the core DOM for use with HTML. DOM
HTML provides the features used to manipulate HTML documents and utilizes a
syntax similar to the traditional JavaScript object models. Basically, this is DOM Level
0 plus capabilities for manipulating all of the HTML element objects.
 DOM CSS Provides the interfaces necessary to manipulate CSS rules
programmatically.
 DOM Events adds event handling to the DOM. These events range from familiar user
interface events such as mouse clicks to DOM-specific events that fire when actions
occur that modify parts of the document tree.
 DOM XML Specifies an extension to the core DOM for use with XML. DOM XML
addresses the particular needs of XML, such as CDATA sections, processing
instructions, namespaces, and so on
Document Tree

When a browser reads this


particular HTML document, it
represents the document in
the form of a tree.
DOM Node properties
Document Subtree
The following relationships are established in this tree:
 The p element has three children : a text node, the
em element, and another text node.
 The text node “A paragraph of” is the first child of
the p element. Its next sibling is the em element, and
it has no previous sibling.
 The em element is at childNodes[1], its previous
sibling is the text node “A paragraph of,” and its next
sibling is another text node containing “is just
an example.”
 The last child of the p element is the text node “is
just an example.” It has a previous sibling that
contains an em element, but it has no next sibling.
 The parent of the em element and its siblings is the p
element.
The text node containing “text” is the first child and
last child of the em element, but it is not a direct
descendant of the p element and has no siblings
Accessing Elements
 There are major four elements of DOM as follows:
 Document: Treats all the HTML documents
 Elements: Tags used inside HTML document
 Text: Content of tags
 Attributes: Here, “href” is an attribute
 HTML Elements:
1. Button
2. Table
3. Head
4. Link
5. Style
6. Div
7. Span
8. header
Access HTML elements using DOM
 From the DOM, users can access HTML elements in five different ways in JavaScript.
• Get HTML element by Id
• Get HTML element by className
• Get HTML element by Name
• Get HTML element by tagName
• Get HTML element by CSS Selector
DOM and HTML Elements
 Finding HTML elements by id

Ex: const element = document.getElementById(“demo");

 Finding HTML elements by tag name: The HTML DOM getElementsByTagName() method is
used to access the HTML elements using the tag name. This function takes single parameter.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM getElementsByTagName</h2>
<p>Finding HTML Elements by Tag Name.</p>
<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 'The text in first paragraph is: ' +
element[0].innerHTML;
</script>

</body>
</html>
 Finding HTML elements by class name
The getElementsByClassName() method in Javascript is used to access HTML elements using
classname. Each element in the returned object can be accessed by its index. The index value will
start with 0.
<!DOCTYPE html> Output:
<html>
<body>
<div class="example">First</div>
<div class="example">Second</div>
Output: at index 0
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!"; Output: at index 1
}
</script>
</body>
</html>
Finding HTML elements by CSS selectors
What is CSS selector?
Consider in HTML we define a div in body as
<body>
<div class =“box”></div>
</body>

How will you access this in CSS??


div.Box
{
Width = 20px; This is CSS
Length =20px; selector
}
 HTML elements can be retrieved using CSS selectors in two ways. The querySelector(CSS selector )
method returns the first element that matches the particular CSS selector.
 The querySelectorAll(CSS Selector) method returns all element that matches the particular CSS selector.
 To use id/class as a parameter users have to add the ‘#‘/’.‘ sign before it. Users can pass directly the tag
name into the above 2 methods.
Syntax:
document.querySelector(selectors);
document.querySelectorAll(selectors);
Finding HTML elements by CSS selectors (Simple Selector)

CSS selectors are used to select the content you want to style. Selectors are the part of CSS rule
set.
CSS selectors select HTML elements according to its id, class, type, attribute etc.
There are several different types of selectors in CSS.
1. CSS Element Selector
CSS
<html>
<body> H1
{
<h1> hello </h1> styling
}
<p> this is para </p> P
</body> {
styling
</html> }
Finding HTML elements by CSS selectors (Simple Selector)
1. CSS Id Selector
The id selector selects the id attribute of an HTML element to select a specific element. An
id is always unique within the page so it is chosen to select a single, unique element.
It is written with the hash character (#), followed by the id of the element.

HTML CSS
<html> H1
<body> {
styling
<h1> hello </h1> }
<p> this is para </p> P
{
<div id = “demo” hello! </div> styling
</body> }
#demo
</html> {

}
Finding HTML elements by CSS selectors (Simple Selector)
CSS Class Selector
The class selector selects HTML elements with a specific class attribute. It is used with a
period character . (full stop symbol) followed by the class name.

HTML CSS
<html> H1
<body> {
styling
<h1> hello </h1> }
<p> this is para </p> P
{
<div class = “demo” hello! </div> styling
</body> }
.demo
</html> {

}
Finding HTML elements by CSS selectors (Simple Selector)
CSS Universal Selector
The universal selector is used as a wildcard character. It selects all the elements on the pages.

HTML CSS
<html> *{
<body> margin =0;
Padding = 0;
<h1> hello </h1> }
<p> this is para </p> The above styling will be for all
the elements in HTML
<div class = “demo” hello! </div>
</body>
</html>
Finding HTML elements by CSS selectors (Simple Selector)

CSS Group Selector


The grouping selector is used to select all the elements with the same style definitions.
Grouping selector is used to minimize the code. Commas are used to separate each selector in
grouping.
CSS
HTML
h1,p
<html>
{
<body> color : red;
<h1> hello </h1>
}
<p> this is para </p>
<div id = “demo” hello! </div>
</body>
</html>
Use of queryselector()
 Consider the following HTML code Consider the following JS code
<!DOCTYPE html>
<html lang="en"> Accessing element:

<head> let element = document.querySelector('h2’)


<title>querySelector() Demo</title>
Accessing class
</head>
<body> let element = document.querySelector('.InterviewB
<h1>Query Selector</h1> Accessing ID
<h2>Learning Query selector method</h2>
let element = document.querySelector('#scaler')
<p id="scaler" class="InterviewBit">I learn on scaler
academy</p>
Document.queryselector(*) – all the elements in
<a href="#" target="_blank"> Link </a>
HTML
<input type = "text" value = "Scaler_topics"> Document.queryselector(h1,p) – group of elements
in HTML but only the first one which will be found
</body>
will be returned.
</html>
DOM with CSS
 Changing HTML Style
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property = new style
 Using Events
 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
Overview of Events and Event Handling
Event handling is done as follows:
 Using traditional HTML event handler attributes directly in markup.
For example:
<p onclick = “myfunction()”>clickme</p>
 Using script to set handlers to be related to an object.
For example:
document.getElementById(“p1”).onclick = myfunction
 Using proprietary methods such as Internet Explorer’s attachEvent() method.
For example:
document.getElementById(“p1”).attachEvent(“onclick”, myfunction)
 Using DOM methods to set event listeners using a node’s addEventListener()
method.
For example:
document.getElementById(“p1”). addEventListner(“click”, myfunction,false)
Overview of Event Models over Time
Overview of Events and Event Handling
Assigning Events using HTML DOM
 onclick event to a button element
 onload and onunload Events
1. The onload and onunload events are triggered when the user enters or
leaves the page.
2. The onload and onunload events can be used to deal with cookies.
 onchange Event
The onchange event occurs when the value of an HTML element is
changed.
 onmouseover and onmouseout Events
 onmousedown, onmouseup and onclick Events
onclick event to a button element
<html>
<body>

<h2>JavaScript DOM HTML Events</h2>


<p>Click "Try it" to display todays date.</p>

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

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

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

function displayDate() { Output:


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

</body>
</html>
onchange Event
<html>
<body>
<p>Select your favorite fruit from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="mango">mango</option>
<option value="apple">apple</option>
<option value="grapes">graps</option>
<option value="pear">pear</option>
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>

</body>
</html>
DOM2 Event Model
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:

The default value is false, which will use the bubbling propagation, when the value is
set to true, the event uses the capturing propagation.
Handling events in DOM2 : addEventListener()
The methods used for event handling in DOM 2 are listed below
addEventListener() and removeEventListener()

The syntax of the addEventListener() method is


Object.addEventListner(event,handler,capture phase);
• object is the node to which the listener is to be bound.
• event is a string indicating the event it is to listen for.
• handler is the function that should be invoked when the event occurs.
• capturePhase is a Boolean indicating whether the handler should be
invoked during the capture phase (true) or bubbling phase (false).
Example:
to register a function changeColor() as the capture-phase
mouseover handler for a paragraph with an id of myText, you might write
the following:
document.getElementById(“myText”).addEventListerner(“mouseover”changeColor,true)
To add a bubble phase handler, simply change the final value to false
Handling events in DOM2 : removeEventListener()
The removeEventListener() method removes event handlers that have been attached
with the addEventListener() method:
Example:
element.removeEventListener("mousemove", myFunction);

Refer to the program: remove_event_handler.html


Event Model Issues
 Event Leakage
 Event Ordering
 Event Bubbling or Capturing
 Event Overload
 Event Synchronization
 Event handling errors
 Cross compatibility
Thank You

You might also like