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

Lesson 6 DOM Manipulation and Event Handling

The document discusses DOM manipulation and event handling in JavaScript, detailing various events and their corresponding event handlers. It explains how to create JavaScript objects, including direct instances, templates, and hash literals, as well as how to interact with the HTML DOM to access and manipulate web page elements. Additionally, it provides examples of using event handlers for form validation and element interaction.

Uploaded by

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

Lesson 6 DOM Manipulation and Event Handling

The document discusses DOM manipulation and event handling in JavaScript, detailing various events and their corresponding event handlers. It explains how to create JavaScript objects, including direct instances, templates, and hash literals, as well as how to interact with the HTML DOM to access and manipulate web page elements. Additionally, it provides examples of using event handlers for form validation and element interaction.

Uploaded by

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

DOM Manipulation and Event Handling

Events & Event Handlers


• Every element on a web page has certain events which can trigger invocation of event handlers
• Attributes are inserted into HTML tags to define events and event handlers
• Examples of events
> A mouse click
> A web page or an image loading
> Mousing over a hot spot on the web page
> Selecting an input box in an HTML form
> Submitting an HTML form
> A keystroke
Events
• onabort - Loading of an image is interrupted
• onblur - An element loses focus
• onchange - The content of a field changes
• onclick - Mouse clicks an object
• ondblclick - Mouse double-clicks an object
• onerror - An error occurs when loading a document or an image
• onfocus - An element gets focus
• onkeydown - A keyboard key is pressed
onkeypress - A keyboard key is pressed or held down
• onkeyup - A keyboard key is released
• onload - A page or an image is finished loading
• onmousedown - A mouse button is pressed
• onmousemove - The mouse is moved
• onmouseout - The mouse is moved off an element
• onmouseover - The mouse is moved over an element
• onmouseup - A mouse button is released

1
 onreset - The reset button is clicked
• onresize - A window or frame is resized
• onselect - Text is selected
• onsubmit - The submit button is clicked
• onunload - The user exits the page
onFocus, onBlur and onChange
• The onFocus, onBlur and onChange events are often used in combination with validation of
form
fields.
• Example: The checkEmail() function will be called whenever the user changes the content of
the field:
<input type="text" size="30"
id="email" onchange="checkEmail()">;
Example & Demo: onblur
<html>
<head>
<script type="text/javascript">
function upperCase() {
var x=document.getElementById("fname").value
document.getElementById("fname").value=x.toUpperCase()
}
</script>
</head>
<body>
Enter your name:
<input type="text" id="fname" onblur="upperCase()">
</body>
</html>

2
onSubmit
• The onSubmit event is used to validate all form fields before submitting it.
• Example: The checkForm() function will be called when the user clicks the submit button in
the form. If
the field values are not accepted, the submit should be canceled. The function checkForm()
returns
either true or false. If it returns true the form will be submitted, otherwise the submit will be
cancelled:
<form method="post" action="xxx.html" onsubmit="return checkForm()">
Example & Demo: onSubmit
<html>
<head>
<script type="text/javascript">
function validate() {
// return true or false based on validation logic
}
</script>
</head>
<body>
<form action="tryjs_submitpage.htm" onsubmit="return validate()">
Name (max 10 chararcters): <input type="text" id="fname" size="20"><br />
Age (from 1 to 100): <input type="text" id="age" size="20"><br />
E-mail: <input type="text" id="email" size="20"><br />
<br />
<input type="submit" value="Submit">
</form>
</body>
</html>

3
JavaScript Object
JavaScript is an Object Oriented Programming (OOP) language
• A JavaScript object has properties and methods
> Example: String JavaScript object has length property and toUpperCase() method
<script type="text/javascript">
var txt="Hello World!"
document.write(txt.length)
document.write(txt.toUpperCase())
</script>
• 3 different ways
> Create a direct instance of an object by using built-in constructor for the Object class
> Create a template (Constructor) first and then create an instance of an object from it
> Create object instance as Hash Literal
Option 1: Creating a Direct Instance of a JavaScript Object
• By invoking the built-in constructor for the Object class
personObj=new Object(); // Initially empty with no properties or methods
• Add properties to it
personObj.firstname="John";
personObj.age=50;
• Add an anonymous function to the personObj
personObj.tellYourage=function(){
alert(“This age is ” + this.age);
}
// You can call then tellYourage function as following
personObj.tellYourage();
Option 1: Creating a Direct Instance
of a JavaScript Object
• Add a pre-defined function

4
function tellYourage(){
alert(“The age is” + this.age);
}
personObj.tellYourage=tellYourage;
• Note that the following two lines of code are doing completely different things
// Set property with a function
personObj.tellYourage=tellYourage;
// Set property with returned value of the function
personObj.tellYourage=tellYourage();
Option 2: Creating a template of a
JavaScript Object
• The template defines the structure of a JavaScript object in the form of a function
• You can think of the template as a constructor
function Person(firstname,lastname,age,eyecolor) {
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.tellYourage=function(){
alert(“This age is ” + this.age);
}
}
Option 2: Creating a template of a
JavaScript Object
• Once you have the template, you can create new instances of the object
myFather=new Person("John","Doe",50,"blue");
myMother=new Person("Sally","Rally",48,"green");
• You can add new properties and functions to new
objects

5
myFather.newField = “some data”;
myFather.myfunction = function() {
alert(this["fullName"] + ” is ” + this.age);
}
Option 3: Creating JavaScript
Object as a Hash Literal
• Create personObj JavaScript object
var personObj = {
firstname: "John",
lastname: "Doe",
age: 50,
tellYourage: function () {
alert(“The age is ” + this.age );
}
tellSomething: function(something) {
alert(something);
}
}
personObj.tellYourage();
personObj.tellSomething(“Life is good!”);
HTML DOM Objects
- Client-side JavaScript adds collection of objects, methods and properties that allow scripts to
interact with HTML documents
o dynamic documents
o client-side programming
• This is done by bindings to the Document Object Model (DOM)
– “The Document Object Model is a platform- and language-neutral interface that will allow
programs and scripts to dynamically access and update the content, structure and style of
documents.”

6
– “The document can be further processed and the results of that processing can be incorporated
back into the presented page.”
• The HTML DOM defines a standard set of objects for HTML, and a standard way to access
and manipulate HTML documents
• All HTML elements, along with their containing text and attributes, can be accessed through
the DOM.
> The contents can be modified or deleted, and new elements can be created.
• The HTML DOM is platform and language independent
> It can be used by any programming language like Java, JavaScript, and VBScript
-The DOM is the tree of nodes corresponding to HTML elements on a page. Can modify, add and remove
nodes on the DOM, which will modify, add, or remove the corresponding element on the page.

HTML DOM Objects


• Anchor object
• Document object
• Event object
• Form and Form Input object
• Frame, Frameset, and IFrame objects
• Image object
• Location object
• Navigator object
 Option and Select objects
• Screen object
• Table, TableHeader, TableRow, TableData objects
• Window object
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.
-Then you can do a lot of things with the document object:

7
Action Example
Finding HTML Elements document.querySelector(CSS selector);
Adding and Deleting Elements document.createElement(element);
Changing HTML Elements element.innerHTML = new html content;
Adding Events Handlers element.addEventListener('event', handler);
Finding HTML Elements
If you want to find the first HTML elements that matches a specified CSS selector
(id, class names, types, attributes, values of attributes, etc), use the querySelector()
method.
For example this javascript statement will return the first paragraph element of
class main:
document.querySelector("p.main");
<body>
<p>my first paragraph</p>
<p class="main">my first main paragraph</p>
<p class="main">my second main paragraph</p>
<a href="http://www.google.com">google</a>
</body>
Finding HTML Elements
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.
For example this javascript statement will return all paragraph elements of class
main:
document.querySelectorAll("p.main");
<body>
<p>my first paragraph</p>

8
<p class="main">my first main paragraph</p>
<p class="main">my second main paragraph</p>
<a href="http://www.google.com">google</a>
</body>
querySelectorAll() method will return a list of all HTML elements that match the
specified CSS query.
const pars = document.querySelectorAll("p.main");
<body>
<p>my first paragraph</p>
<p class="main">my first main paragraph</p>
<p class="main">my second main paragraph</p>
<a href="http://www.google.com">google</a>
</body>

Document Object: Write text


<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Document Object: Write text with Formatting to the output
<html>
<body>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>")

9
</script>
</body>
</html>
Document Object: Use getElementById()
<html>
<head>
<script type="text/javascript">
function getElement() {
var x=document.getElementById("myHeader")
alert("I am a " + x.tagName + " element")
}
</script>
</head>
<body>
<h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1>
</body>
</html>
Document Object: Use getElementsByName()
<html>
<head>
<script type="text/javascript">
function getElements() {
var x=document.getElementsByName("myInput")
alert(x.length + " elements!")
}
</script>
</head>
<body>

10
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<br />
<input type="button" onclick="getElements()" value="How many elements named
'myInput'?">
</body>
</html>
Document Object: Return the innerHTML of the first anchor in a document
<html>
<body>
<a name="first">First anchor</a><br />
<a name="second">Second anchor</a><br />
<a name="third">Third anchor</a><br />
<br />
InnerHTML of the first anchor in this document:
<script type="text/javascript">
document.write(document.anchors[0].innerHTML)
</script>
</body>
</html>
Document Object: Access an item in a collection
<html>
<body>
<form id="Form1" name="Form1">
Your name: <input type="text">
</form>
<form id="Form2" name="Form2">

11
Your car: <input type="text">
</form>
<p>
To access an item in a collection you can either use the number or the name of the item:
</p>
<script type="text/javascript">
document.write("<p>The first form's name is: " + document.forms[0].name + "</p>")
document.write("<p>The first form's name is: " + document.getElementById("Form1").name
+ "</p>")
</script>
</body>
</html>
Event Object: Which element was clicked?
<html>
<head>
<script type="text/javascript">
function whichElement(e) {
var targ
if (!e) var e = window.event
if (e.target) targ = e.target
else if (e.srcElement) targ = e.srcElement
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode
var tname
tname=targ.tagName
alert("You clicked on a " + tname + " element.")
}
</script>

12
</head>
<body onmousedown="whichElement(event)">
<p>Click somewhere in the document. An alert box will alert the tag name of the element you
clicked on.</p>
<h3>This is a header</h3>
<p>This is a paragraph</p>
<img border="0" src="ball16.gif" width="29" height="28" alt="Ball">
</body>
</html>
Event Object: Which event type occurred?
<html>
<head>
<script type="text/javascript">
function whichType(event) {
alert(event.type)
}
</script>
</head>
<body onmousedown="whichType(event)">
<p>
Click on the document. An alert box will alert which type of event occurred.
</p>
</body>
</html>

13

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