You are on page 1of 27

Javascript Part 2

(Some Advance feature)


-By Rupam Patel
Window setInterval() Method
Definition and Usage
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.

The ID value returned by setInterval() is used as the parameter for the clearInterval() method.

Tip: 1000 ms = 1 second.

Tip: To execute a function only once, after a specified number of milliseconds, use the setTimeout() method.

Syntax
setInterval(function, milliseconds, param1, param2, ...)
Window setInterval() Method
Example Example
You can also refer to a "named" function; Alert Display the current time (the setInterval() method
"Hello" every 3 seconds (3000 milliseconds): will execute the function once every 1 second, just
like a digital watch):
var myVar;
var myVar = setInterval(myTimer, 1000);
function myFunction() {
myVar = setInterval(alertFunc, 3000); function myTimer() {
} var d = new Date();
var t = d.toLocaleTimeString();
function alertFunc() {
alert("Hello!"); document.getElementById("demo").innerHTML
} = t;
}
What You Will Learn
In the next chapters of this tutorial you will learn:
When a web page is loaded, the browser creates a Document Object Model of the page.
● How to change the content of HTML elements
The HowDOM
● HTML to change
modelthe style (CSS) as
is constructed of HTML
a tree elements
of Objects:
● How to react to HTML DOM events
● How to add and delete HTML elements

The HTML DOM Tree of Objects


The HTML DOM

With the object model, JavaScript gets all the


power it needs to create dynamic HTML:
What You Will Learn
● JavaScript can change all the HTML elements In the next chapters of this tutorial you will learn:
in the page
● How to change the content of HTML elements
● JavaScript can change all the HTML attributes
● How to change the style (CSS) of HTML
in the page
elements
● JavaScript can change all the CSS styles in
● How to react to HTML DOM events
the page
● How to add and delete HTML elements
● 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
The HTML DOM

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.
The HTML DOM

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

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


The HTMLCollection Object
An HTMLCollection object is an array-like list of HTML elements.

Methods like the getElementsByTagName() returns an HTMLCollection.

Properties and Methods


The following properties and methods can be used on a HTMLCollection object:

Property / Method Description

item() Returns the element at the specified index in an HTMLCollection

length Returns the number of elements in an HTMLCollection

namedItem() Returns the element with the specified ID, or name, in an HTMLCollection
The Browser There are no official standards for
the Browser Object Model (BOM).

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");
The Window Object

Window Size The browser window (the browser viewport) is NOT


including toolbars and scrollbars.
Two properties can be used to determine the size
of the browser window.
For Internet Explorer 8, 7, 6, 5:
Both properties return the sizes in pixels:
● document.documentElement.clientHeight
● window.innerHeight - the inner height of
● document.documentElement.clientWidth
the browser window (in pixels)
● or
● window.innerWidth - the inner width of the
● document.body.clientHeight
browser window (in pixels)
● document.body.clientWidth

The browser window (the browser viewport) is NOT


including toolbars and scrollbars.
The Window Object

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
The Window Object

The screen.width property returns the width of the


Window Screen visitor's screen in pixels.

The window.screen object can be written without


the window prefix. Example
Properties:
Display the width of the screen in pixels:
● screen.width
● screen.height
● screen.availWidth document.getElementById("demo").innerHTML =
● screen.availHeight
● screen.colorDepth "Screen Width: " + screen.width;
● screen.pixelDepth
The Window Object -Screen Object

● Window Screen Window Screen Available


Available Width Height
● The screen.availWidth property returns The screen.availHeight property returns the height
the width of the visitor's screen, in pixels, of the visitor's screen, in pixels, minus interface
minus interface features like the Windows features like the Windows Taskbar.
Taskbar.
● Example ● Example
● Display the available width of the screen in
● Display the available height of the screen in
pixels:
pixels:
● document.getElementById("demo").inner ● document.getElementById("demo").innerHTML
HTML ="Available Screen Width: " + ="Available Screen Height: " +
screen.availWidth; screen.availHeight;
The Window Object -Screen Object

● Very old computers, and old cell phones used 8


Window Screen Color bits: 256 different "VGA colors".

Depth
The screen.colorDepth property returns the
number of bits used to display one color. Example
All modern computers use 24 bit or 32 bit hardware
for color resolution: Display the color depth of the screen in bits:

● 24 bits = 16,777,216 different "True


Colors" ● document.getElementById("demo").innerHTML
● 32 bits = 4,294,967,296 different "Deep ="Screen Color Depth: " +screen.colorDepth;
Colors"

Older computers used 16 bits: 65,536 different


"High Colors" resolution.
The Window Object -JavaScript Popup Boxes
● Alert Box
● An alert box is often used if you want to make sure information comes through to the user.
● When an alert box pops up, the user will have to click "OK" to proceed.

Syntax
window.alert("sometext");

Example
alert("I am an alert box!");
The Window Object -JavaScript Popup Boxes
Confirm Box The window.confirm() method can be written
without the window prefix.

A confirm box is often used if you want the user to


verify or accept something.
Example

When a confirm box pops up, the user will have to if (confirm("Press a button!")) {
click either "OK" or "Cancel" to proceed.
txt = "You pressed OK!";
If the user clicks "OK", the box returns true. If the
user clicks "Cancel", the box returns false. } else {

txt = "You pressed Cancel!";


Syntax
window.confirm("sometext"); }
The Window Object -JavaScript Popup Boxes
Prompt Box Example
var person = prompt("Please enter your
A prompt box is often used if you want the user to name", "Harry Potter");
input a value before entering a page.
if (person == null || person == "") {
When a prompt box pops up, the user will have to txt = "User cancelled the prompt.";
click either "OK" or "Cancel" to proceed after } else {
entering an input value. txt = "Hello " + person + "! How are
you today?";
If the user clicks "OK" the box returns the input }
value. If the user clicks "Cancel" the box returns
null.

Syntax
window.prompt("sometext","defaultText");
The Window Object -JavaScript Popup Boxes
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the character n.

Example

alert("Hello\nHow are you?");


The Window Object

The window.navigator object contains


information about the visitor's browser.

Window Navigator
The window.navigator object can be written
without the window prefix.

Some examples:

● navigator.appName
● navigator.appCodeName
● navigator.platform
The Window Object

Window Location
The window.location object can be written without the window prefix.

Some examples:

● window.location.href returns the href (URL) of the current page


● window.location.hostname returns the domain name of the web host
● window.location.pathname returns the path and filename of the current page
● window.location.protocol returns the web protocol used (http: or https:)
● window.location.assign() loads a new document
The Window Object

The window.history object contains the browsers history.

Window History
The window.history object can be written without the window prefix.

To protect the privacy of the users, there are limitations to how JavaScript can access this object.

Some methods:

● history.back() - same as clicking back in the browser


● history.forward() - same as clicking forward in the browser


JavaScript Cookies
● When a user visits a web page, his/her name can
Cookies let you store user information in web
be stored in a cookie.
pages.
● Next time the user visits the page, the cookie
"remembers" his/her name.

Cookies are saved in name-value pairs like:


What are Cookies?
username = John Doe
Cookies are data, stored in small text files, on your
computer. When a browser requests a web page from a server,
cookies belonging to the page are added to the request.
When a web server has sent a web page to a This way the server gets the necessary data to
browser, the connection is shut down, and the "remember" information about users.
server forgets everything about the user.

Cookies were invented to solve the problem "how None of the examples below will work if your browser has
to remember information about the user": local cookies support turned off.
JavaScript Cookies

Create a Cookie with document.cookie = "username=John Doe;


expires=Thu, 18 Dec 2013 12:00:00 UTC";
JavaScript With a path parameter, you can tell the browser what
path the cookie belongs to. By default, the cookie belongs
JavaScript can create, read, and delete cookies
to the current page.
with the document.cookie property.

With JavaScript, a cookie can be created like this: document.cookie = "username=John Doe;
expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/"
;

document.cookie = "username=John Doe";

You can also add an expiry date (in UTC time). By


default, the cookie is deleted when the browser is
closed:

You might also like