Ad

Ad

Sunday, 4 May 2014

JavaScript Timing Events


1
2
3
4
5
6
7
8
9
10
11
12
JavaScript can be executed in time-intervals.
This is called timing events.

JavaScript Timing Events

With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
  • setInterval() - executes a function, over and over again, at specified time intervals
  • setTimeout() - executes a function, once, after waiting a specified number of milliseconds
Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.

The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

Syntax

window.setInterval("javascript function",milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter of setInterval() should be a function.
The second parameter indicates the length of the time-intervals between each execution.
Note: There are 1000 milliseconds in one second.

Example

Alert "hello" every 3 seconds:
setInterval(function(){alert("Hello")},3000);

Try it Yourself »
The example show you how the setInterval() method works, but it is not very likely that you want to alert a message every 3 seconds.
Below is an example that will display the current time. The setInterval() method is used to execute the function once every 1 second, just like a digital watch.

Example

Display the current time:
var myVar=setInterval(function(){myTimer()},1000);

function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}

Try it Yourself »


How to Stop the Execution?

The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.

Syntax

window.clearInterval(intervalVariable)
The window.clearInterval() method can be written without the window prefix.
To be able to use the clearInterval() method, you must use a global variable when creating the interval method:
myVar=setInterval("javascript function",milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.

Example

Same example as above, but we have added a "Stop time" button:
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>

<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function myStopFunction()
{
clearInterval(myVar);
}
</script>

Try it Yourself »


The setTimeout() Method

Syntax

window.setTimeout("javascript function",milliseconds);
The window.setTimeout() method can be written without the window prefix.
The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
The first parameter of setTimeout() should be a function.
The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.

Example

Wait 3 seconds, then alert "Hello":
setTimeout(function(){alert("Hello")},3000);

Try it Yourself »


How to Stop the Execution?

The clearTimeout() method is used to stop the execution of the function specified in the setTimeout() method.

Syntax

window.clearTimeout(timeoutVariable)
The window.clearTimeout() method can be written without the window prefix.
To be able to use the clearTimeout() method, you must use a global variable when creating the timeout method:
myVar=setTimeout("javascript function",milliseconds);
Then, if the function has not already been executed, you will be able to stop the execution by calling the clearTimeout() method.

Example

Same example as above, but we have added a "Stop the alert" button:
var myVar;

function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}

function myStopFunction()
{
clearTimeout(myVar);
}

Try it Yourself »

JavaScript Popup Boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

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");
The window.alert method can be written without the window prefix.

Example

alert("I am an alert box!");

Try it Yourself »


Confirm Box

A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax

window.confirm("sometext");
The window.confirm() method can be written without the window prefix.

Example

var r=confirm("Press a button");
if (r==true)
  {
  x="You pressed OK!";
  }
else
  {
  x="You pressed Cancel!";
  }

Try it Yourself »


Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
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.prompt() method can be written without the window prefix.

Example

var person=prompt("Please enter your name","Harry Potter");

if (person!=null)
  {
  x="Hello " + person + "! How are you today?";
  document.getElementById("demo").innerHTML=x;
  }

Try it Yourself »


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?");

Try it Yourself »

JavaScript Window Navigator

The window.navigator object contains information about the visitor's browser.

Window Navigator

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

Example

<div id="example"></div>

<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;

</script>

Try it Yourself »


Warning !!!

The information from the navigator object can often be misleading, and should not be used to detect browser versions because:
  • The navigator data can be changed by the browser owner
  • Some browsers misidentify themselves to bypass site tests
  • Browsers cannot report new operating systems, released later than the browser

Browser Detection

Since the navigator object can be misleading about browser detection, using object detection can be used to sniff out different browsers.
Since different browsers support different objects, you can use objects to detect browsers. For example, since only Opera supports the property "window.opera", you can use that to identify Opera.
Example: if (window.opera) {...some action...}

JavaScript Window History

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

Window History Back

The history.back() method loads the previous URL in the history list.
This is the same as clicking the Back button in the browser.

Example

Create a back button on a page:
<html>
<head>
<script>
function goBack()
  {
  window.history.back()
  }
</script>
</head>
<body>

<input type="button" value="Back" onclick="goBack()">

</body>
</html>
The output of the code above will be:


Window History Forward

The history forward() method loads the next URL in the history list.
This is the same as clicking the Forward button in the browser.

Example

Create a forward button on a page:
<html>
<head>
<script>
function goForward()
  {
  window.history.forward()
  }
</script>
</head>
<body>

<input type="button" value="Forward" onclick="goForward()">

</body>
</html>
The output of the code above will be:

JavaScript Window Location

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

Window Location

The window.location object can be written without the window prefix.
Some examples:
  • location.hostname returns the domain name of the web host
  • location.pathname returns the path and filename of the current page
  • location.port returns the port of the web host (80 or 443)
  • location.protocol returns the web protocol used (http:// or https://)

Window Location Href

The location.href property returns the URL of the current page.

Example

Return the entire URL (of the current page):
<script>

document.write(location.href);

</script>
The output of the code above is:
http://www.w3schools.com/js/js_window_location.asp


Window Location Pathname

The location.pathname property returns the path name of a URL.

Example

Return the path name of the current URL:
<script>

document.write(location.pathname);

</script>
The output of the code above is:
/js/js_window_location.asp


Window Location Assign

The location.assign() method loads a new document.

Example

Load a new document:
<html>
<head>
<script>
function newDoc()
  {
  window.location.assign("http://www.w3schools.com")
  }
</script>
</head>
<body>

<input type="button" value="Load new document" onclick="newDoc()">

</body>
</html>

Try it Yourself »

JavaScript Window Screen

The window.screen object contains information about the user's screen.

Window Screen

The window.screen object can be written without the window prefix.
Some properties:
  • screen.availWidth - available screen width
  • screen.availHeight - available screen height

Window Screen Available Width

The screen.availWidth property returns the width of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.

Example

Return the available width of your screen:
<script>

document.write("Available Width: " + screen.availWidth);

</script>
The output of the code above will be:
Available Width: 1024

Try it Yourself »


Window Screen Available Height

The screen.availHeight property returns the height of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.

Example

Return the available height of your screen:
<script>

document.write("Available Height: " + screen.availHeight);

</script>
The output of the code above will be:
Available Height: 738

Try it Yourself »

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

Three different properties can be used to determine the size of the browser window (the browser viewport, NOT including toolbars and scrollbars).
For Internet Explorer, Chrome, Firefox, Opera, and Safari:
  • window.innerHeight - the inner height of the browser window
  • window.innerWidth - the inner width of the browser window
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;

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

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 Nodelist

A nodelist is an array of nodes (like an array of all HTML elements)

HTML DOM Node List

The getElementsByTagName() method returns a node list. A node list is an array of nodes.
The following code selects all <p> nodes in a document:

Example

var x=document.getElementsByTagName("p");
The nodes can be accessed by index number. To access the second <p> you can write:
y=x[1];

Try it Yourself »
Note: The index starts at 0.

HTML DOM Node List Length

The length property defines the number of nodes in a node-list.
You can loop through a node-list by using the length property:

Example

x=document.getElementsByTagName("p");

for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}

Try it Yourself »
Example explained:
  1. Get all <p> element nodes
  2. For each <p> element, output the value of its text node

JavaScript HTML DOM Elements (Nodes)

Adding and Removing Nodes (HTML Elements)

Creating New HTML Elements (Nodes)

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

 Example

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);

var element=document.getElementById("div1");
element.appendChild(para);
</script>

Try it Yourself »


Example Explained 

This code creates a new <p> element:
var para=document.createElement("p");
To add text to the <p> element, you must create a text node first. This code creates a text node:
var node=document.createTextNode("This is a new paragraph.");
Then you must append the text node to the <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.
This code finds an existing element:
var element=document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);


Creating new HTML Elements - insertBefore()

The appendChild() method in the previous example, appended the new element as the last child of the parent.
If you don't want that you can use the insertBefore() method:

 Example

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);

var element=document.getElementById("div1");
var child=document.getElementById("p1");
element.insertBefore(para,child);
</script>

Try it Yourself »


Removing Existing HTML Elements

To remove an HTML element, you must know the parent of the element:

Example

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>

Try it Yourself »


Example Explained 

This HTML document contains a <div> element with two child nodes (two <p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
var parent=document.getElementById("div1");
Find the <p> element with id="p1":
var child=document.getElementById("p1");
Remove the child from the parent:
parent.removeChild(child);

NoteIt would be nice to be able to remove an element without referring to the parent.
But sorry. The DOM needs to know both the element you want to remove, and its parent.
Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:
var child=document.getElementById("p1");
child.parentNode.removeChild(child);


Replacing HTML Elements 

To replace an element to the HTML DOM, use the replaceChild() method:

Example

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);

var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.replaceChild(para,child);
</script>

Try it Yourself »