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 Window Screen

« Previous

Next Chapter »

 

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

 

Window Screen

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

Properties:

  • screen.width
  • screen.height
  • screen.availWidth
  • screen.availHeight
  • screen.colorDepth
  • screen.pixelDepth

 

Window Screen Width

The screen.width property returns the width of the visitor's screen in pixels.

Example

Display the width of the screen in pixels:

"ScreenWidth: " + screen.width

Result will be:

Screen Width: 1360 


Try it Yourself » 

 

 

Window Screen Height

The screen.height property returns the height of the visitor's screen in pixels.

Example

Display the height of the screen in pixels:

"Screen Height: " + screen.height

Result will be:

Screen Height: 768


Try it Yourself » 

 

 

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

Display the available width of the screen in pixels:

"Available Screen Width: " + screen.availWidth

Result will be:

Available Screen Width: 1360


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

Display the available height of the screen in pixels:

"Available Screen Height: " + screen.availHeight

Result will be:

Available Screen Height: 728


Try it Yourself » 

 

 

Window Screen Color Depth

The screen.colorDepth property returns the number of bits used to display one color.

All modern computers use 24 or 32 bits hardware to display 16,777,216 different colors ("True Colors").

Older computers used 16 bits, which gives a maximum of 65,536 different colors ("High Colors")

Very old computers, and old cell phones used 8 bits ("VGA colors").

Example

Display the color depth of the screen in bits:

"Screen Color Depth: " + screen.colorDepth

Result will be:

Screen Color Depth: 24


Try it Yourself » 

 

 

Some computers report 32. Most computers report 24. Both display "True Colors" (16,777,216 different colors).

 

 

Window Screen Pixel Depth

The screen.pixelDepth property returns the pixel depth of the screen.

Example

Display the pixel depth of the screen in bits:

"Screen Pixel Depth: " + screen.pixelDepth

Result will be:

Screen Pixel Depth: 24


Try it Yourself » 

 

 

For modern computers, Color Depth and Pixel Depth are equal.

 

 

JavaScript Window Location

« Previous

Next Chapter »

 

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.href returns the href (URL) of the current page
  • location.hostname returns the domain name of the web host
  • location.pathname returns the path and filename of the current page
  • location.protocol returns the web protocol used (http:// or https://)
  • location.assign loads a new document

 

Window Location Href

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

Example

Display the href (URL) of the current page:

"Page location is " + location.href;

Result is:

Page location is http://www.w3schools.com/js/js_window_location.asp 


Try it Yourself » 

 

 

Window Location Hostname

The location.hostname property returns the name of the internet host (of the current page).

Example

Display the name of the host:

"Page host is " + location.hostname;

Result is:

Page hostname is www.w3schools.com 


Try it Yourself » 

 

 

Window Location Pathname

The location.pathname property returns the path name of page.

Example

Display the path name of the current URL:

"Page path is " + location.pathname; 

Result is:

/js/js_window_location.asp


Try it Yourself » 

 

 

Window Location Protocol

The location.protocol property returns the web protocol of the page.

Example

Display the web protocol:

"Page protocol is " + location.protocol; 

Result is:

Page protocol is http:


Try it Yourself » 

 

 

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> 

 

 

 

JavaScript Window History

« Previous

Next Chapter »

 

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>

 

 

JavaScript Window Navigator

« Previous

Next Chapter »

 

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

 

Navigator Cookie Enabled

The property cookieEnabled returns true if cookies are enabled, otherwise false:

Example

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

<script>
document.getElementById("demo").innerHTML =
"Cookies Enabled is " + navigator.cookieEnabled;
</script>


Try it Yourself » 

 

 

The Browser Names

The properties appName and appCodeName return the name of the browser:

Example

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

<script>
document.getElementById("demo").innerHTML =
"Name is " + navigator.appName + ". Code name is " + navigator.appCodeName;
</script>


Try it Yourself » 

 

Did you know?

IE11, Chrome, Firefox, and Safari return appName "Netscape".

Chrome, Firefox, IE, Safari, and Opera all return appCodeName "Mozilla".

 

The Browser Engine

The property product returns the engine name of the browser:

Example

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

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


Try it Yourself » 

 

 

The Browser Version I

The property appVersion returns version information about the browser:

Example

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

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


Try it Yourself » 

 

 

The Browser Version II

The property userAgent also returns version information about the browser:

Example

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

<script>
document.getElementById("demo").innerHTML = navigator.userAgent;
</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:

  • Different browsers can use the same name
  • 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

 

The Browser Platform

The property platform returns the browser platform (operating system):

Example

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

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


Try it Yourself » 

 

 

The Browser Language

The property language returns the browser's language:

Example

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

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


Try it Yourself » 

 

 

Is Java Enabled?

The method javaEnabled() returns true if Java is enabled:

Example

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

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

 

 

 

JavaScript Popup Boxes

« Previous

Next Chapter »

 

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) {
    document.getElementById("demo").innerHTML =
    "Hello " + person + "! How are you today?";
}


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

 

 

 

JavaScript Timing Events

« Previous

Next Chapter »

 

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();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}


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="clearInterval(myVar)">Stop time</button>

<script>
var myVar = setInterval(function () {myTimer()}, 1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</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

Click a button. Wait 3 seconds. The page will alert "Hello":

<button onclick = "setTimeout(function(){alert('Hello')},3000)">Try it</button>


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 with an added "Stop" button:

<button onclick="myVar=setTimeout(function(){alert('Hello')},3000)">Try it</button>

<button onclick="clearTimeout(myVar)">Try it</button>

 

 

 

JavaScript Cookies

« Previous

Next Chapter »

 

Cookies let you store user information in web pages.

 

What are Cookies?

Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, the cookie "remembers" his name.

Cookies are saved in name-value pairs like:

username=John Doe 

When a browser request a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

 

Create a Cookie with JavaScript

JavaScript can create, read, and delete cookies with the document.cookie property.

With JavaScript, a cookie can be created like this:

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:

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

 

Read a Cookie with JavaScript

With JavaScript, cookies can be read like this:

var x = document.cookie;

 

 

document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

 

 

Change a Cookie with JavaScript

With JavaScript, you can change a cookie the same way as you create it:

document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

The old cookie is overwritten.

 

Delete a Cookie with JavaScript

Deleting a cookie is very simple. Just set the expires parameter to a passed date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; 

Note that you don't have to specify a cookie value when you delete a cookie.

 

The Cookie String

The document.cookie property looks like a normal text string. But it is not.

Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.

If you set a new cookie, older cookies are not overwritten. The new cookie is added to document.cookie, so if you read document.cookie again you will get something like:

cookie1=value; cookie2=value;

      

If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the cookie value in the cookie string.

 

JavaScript Cookie Example

In the example to follow, we will create a cookie that stores the name of a visitor.

The first time a visitor arrives to the web page, he will be asked to fill in his name. The name is then stored in a cookie.

The next time the visitor arrives at the same page, he will get a welcome message.

For the example we will create 3 JavaScript functions:

  1. A function to set a cookie value
  2. A function to get a cookie value
  3. A function to check a cookie value

 

A Function to Set a Cookie

First, we create a function that stores the name of the visitor in a cookie variable:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;

Example explained:

The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).

The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.

 

A Function to Get a Cookie

Then, we create a function that returns the value of a specified cookie:

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";

Function explained:

Take the cookiename as parameter (cname).

Create a variable (name) with the text to search for (cname + "=").

Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')).

Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]).

If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,c.length).

If the cookie is not found, return "".

 

A Function to Check a Cookie

Last, we create the function that checks if a cookie is set.

If the cookie is set it will display a greeting.

If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:

function checkCookie() {
    var username=getCookie("username");
    if (username!="") {
        alert("Welcome again " + username);
    }else{
        username = prompt("Please enter your name:", "");
        if (username != "" && username != null) {
            setCookie("username", username, 365);
        }
    }

 

 

All Together Now

Example

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}


Try it Yourself » 

The example above runs the checkCookie() function when the page loads.