Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

JavaScript Events BOm and DOm methods (1)

Uploaded by

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

JavaScript Events BOm and DOm methods (1)

Uploaded by

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

JavaScript Events

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML Events
An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

Example

<button onclick="document.getElementById('demo').innerHTML = Date()">The time


is?</button>

In the example above, the JavaScript code changes the content of the element with id="demo".

In the next example, the code changes the content of its own element (using this.innerHTML):

<!DOCTYPE html>
<html>
<body>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time


is?</button>
<p id="demo"></p>

</body>
</html>

Output - Tue Dec 03 2019 11:20:26 GMT-0800 (Pacific Standard Time)

Example
<button onclick="this.innerHTML = Date()">The time is?</button>

JavaScript code is often several lines long. It is more common to see event attributes calling
functions:

<!DOCTYPE html>
<html>
<body>

<button onclick="this.innerHTML=Date()">The time is?</button>

</body>
</html>
Output - Tue Dec 03 2019 11:20:26 GMT-0800 (Pacific Standard Time)

Example

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


<!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>

Output

Click the button to display the date.


Tue Dec 03 2019 11:23:18 GMT-0800 (Pacific Standard Time)

Common HTML Events


Here is a list of some common HTML events:

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

 Things that should be done every time a page loads


 Things that should be done when the page is closed
 Action that should be performed when a user clicks a button
 Content that should be verified when a user inputs data
 And more ...

Many different methods can be used to let JavaScript work with events:

 HTML event attributes can execute JavaScript code directly


 HTML event attributes can call JavaScript functions
 You can assign your own event handler functions to HTML elements
 You can prevent events from being sent or being handled
 And more ...

You will learn a lot more about events and event handlers in the HTML DOM chapters.

JavaScript Window - The Browser Object


Model

The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.

The Browser Object Model (BOM)


There are no official standards for the Browser Object Model (BOM).

Since modern browsers have implemented (almost) the same methods and properties for
JavaScript interactivity, it is often referred to, as methods and properties of the BOM.

The Window Object


The window object is supported by all browsers. It represents the browser's window.

All global JavaScript objects, functions, and variables automatically become members of the
window object.

Global variables are properties of the window object.

Global functions are methods of the window object.

Even the document object (of the HTML DOM) is a property of the window object:

window.document.getElementById("header");

is the same as:

document.getElementById("header");

Window Size
Two properties can be used to determine the size of the browser window.

Both properties return the sizes in pixels:

 window.innerHeight - the inner height of the browser window (in pixels)


 window.innerWidth - the inner width of the browser window (in pixels)

The browser window (the browser viewport) is NOT including toolbars and scrollbars.

For Internet Explorer 8, 7, 6, 5:

 document.documentElement.clientHeight
 document.documentElement.clientWidth
 or
 document.body.clientHeight
 document.body.clientWidth

A practical JavaScript solution (covering all browsers):

Example

var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

The example displays the browser window's height and width: (NOT including
toolbars/scrollbars)

<!DOCTYPE html>
<html>
<body>

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

<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
</script>

</body>
</html>

Output- Browser inner window width: 668, height: 486.

Other Window Methods


Some other methods:

 window.open() - open a new window


 window.close() - close the current window
 window.moveTo() - move the current window
 window.resizeTo() - resize the current window

JavaScript HTML DOM

With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.
The HTML DOM (Document Object Model)
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 You Will Learn


In the next chapters of this tutorial you will learn:

 How to change the content of HTML elements


 How to change the style (CSS) of HTML elements
 How to react to HTML DOM events
 How to add and delete HTML elements

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

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

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":
Example

<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.

Output- My First Page


Hello World!

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>.

JavaScript HTML 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


Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements


Property Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element

Adding and Deleting Elements


Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream

Adding Events Handlers


Method Description
document.getElementById(id).onclick =
Adding event handler code to an onclick event
function(){code}
Finding HTML Objects
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and
properties. These are still valid in HTML5.

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

Property Description DOM


document.anchors Returns all <a> elements that have a name attribute 1
document.applets Returns all <applet> elements (Deprecated in HTML5) 1
document.baseURI Returns the absolute base URI of the document 3
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the document server 1
document.domConfig Obsolete. Returns the DOM configuration 3
document.embeds Returns all <embed> elements 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <img> elements 1
document.implementation Returns the DOM implementation 3
document.inputEncoding Returns the document's encoding (character set) 3
document.lastModified Returns the date and time the document was updated 3
Returns all <area> and <a> elements that have a href
document.links 1
attribute
document.readyState Returns the (loading) status of the document 3
document.referrer Returns the URI of the referrer (the linking document) 1
document.scripts Returns all <script> elements 3
document.strictErrorChecking Returns if error checking is enforced 3
document.title Returns the <title> element 1
document.URL Returns the complete URL of the document 1

JavaScript HTML DOM Elements

This page 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":

Example

var myElement = document.getElementById("intro");

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.

<!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>
var myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script>

</body>
</html>

output

Finding HTML Elements by Id


Hello World!

This example demonstrates the getElementsById method.

The text from the intro paragraph is Hello World!

Finding HTML Elements by Tag Name


This example finds all <p> elements:

Example

var x = document.getElementsByTagName("p");

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

Example

var x = document.getElementById("main");
var y = x.getElementsByTagName("p");

----------------------------------------------------------
<!DOCTYPE html>
<html>
<body>

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

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

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

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

</body>
</html>

output

Finding HTML Elements by Tag Name


Hello World!
This example demonstrates the getElementsByTagName method.
The text in first paragraph (index 0) is: Hello World!
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".

Example

var x = document.getElementsByClassName("intro");

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

---------------------------------------------------------

<!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>
var x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>

</body>
</html>

Output –
Finding HTML Elements by Class Name
Hello World!
The DOM is very useful.
This example demonstrates the getElementsByClassName method.
The first paragraph (index 0) with class="intro": The DOM is very useful.

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".

Example

var x = document.querySelectorAll("p.intro");

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

<!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>
var x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>

</body>
</html>

Output
Finding HTML Elements by Query Selector
Hello World!
The DOM is very useful.
This example demonstrates the querySelectorAll method.
The first paragraph (index 0) with class="intro": The DOM is very useful.

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:

Example

var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;

The following HTML objects (and object collections) are also accessible:

 document.anchors
 document.body
 document.documentElement
 document.embeds
 document.forms
 document.head
 document.images
 document.links
 document.scripts
 document.title

JavaScript HTML DOM - Changing 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: Wed Dec 04 2019 10:48:40 GMT-0800 (Pacific Standard Time)

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

Example

<!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:

Example

<html>
<body>

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

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

</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!"

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

Example

<!DOCTYPE html>
<html>
<body>

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

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

</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:

Example

<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="smiley.gif">

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

</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"

You might also like