The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
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 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");
Two properties can be used to determine the size of the browser window.
Both properties return the sizes in pixels:
The browser window (the browser viewport) is NOT including toolbars and scrollbars.
For Internet Explorer 8, 7, 6, 5:
A practical JavaScript solution (covering all browsers):
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)
Some other methods:
The window.screen object contains information about the user's screen.
The window.screen object can be written without the window prefix.
Properties:
The screen.width property returns the width of the visitor's screen in pixels.
Display the width of the screen in pixels:
document.getElementById("demo").innerHTML =
"Screen Width: " + screen.width;
Result will be:
Try it Yourself »
The screen.height property returns the height of the visitor's screen in pixels.
Display the height of the screen in pixels:
document.getElementById("demo").innerHTML =
"Screen Height: " + screen.height;
Result will be:
Try it Yourself »
The screen.availWidth property returns the width of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.
Display the available width of the screen in pixels:
document.getElementById("demo").innerHTML =
"Available Screen Width: " + screen.availWidth;
Result will be:
Try it Yourself »
The screen.availHeight property returns the height of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.
Display the available height of the screen in pixels:
document.getElementById("demo").innerHTML =
"Available Screen Height: " + screen.availHeight;
Result will be:
Try it Yourself »
The screen.colorDepth property returns the number of bits used to display one color.
All modern computers use 24 bit or 32 bit hardware for color resolution:
Older computers used 16 bits: 65,536 different "High Colors" resolution.
Very old computers, and old cell phones used 8 bits: 256 different "VGA colors".
Display the color depth of the screen in bits:
document.getElementById("demo").innerHTML =
"Screen Color Depth: " + screen.colorDepth;
Result will be:
Try it Yourself »
The #rrggbb (rgb) values used in HTML represents "True Colors" (16,777,216 different colors)
The screen.pixelDepth property returns the pixel depth of the screen.
Display the pixel depth of the screen in bits:
document.getElementById("demo").innerHTML =
"Screen Pixel Depth: " + screen.pixelDepth;
Result will be:
Try it Yourself »
For modern computers, Color Depth and Pixel Depth are equal.
The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
The window.location object can be written without the window prefix.
Some examples:
The window.location.href property returns the URL of the current page.
Display the href (URL) of the current page:
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
Result is:
Try it Yourself »
The window.location.hostname property returns the name of the internet host (of the current page).
Display the name of the host:
document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;
Result is:
Try it Yourself »
The window.location.pathname property returns the pathname of the current page.
Display the path name of the current URL:
document.getElementById("demo").innerHTML =
"Page path is " + window.location.pathname;
Result is:
Try it Yourself »
The window.location.protocol property returns the web protocol of the page.
Display the web protocol:
document.getElementById("demo").innerHTML =
"Page protocol is " + window.location.protocol;
Result is:
Try it Yourself »
The window.location.port property returns the number of the internet host port (of the current page).
Display the name of the host:
document.getElementById("demo").innerHTML =
"Port
number is " + window.location.port;
Result is:
Try it Yourself »
Most browsers will not display default port numbers (80 for http and 443 for https)
The window.location.assign() method loads a new document.
Load a new document:
<html>
<head>
<script>
function newDoc() {
window.location.assign("https://www.w3schools.com")
}
</script>
</head>
<body>
<input type="button" value="Load new document"
onclick="newDoc()">
</body>
</html>
Try it Yourself »
The window.history object contains the browsers 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:
The history.back() method loads the previous URL in the history list.
This is the same as clicking the Back button in the browser.
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:
The history forward() method loads the next URL in the history list.
This is the same as clicking the Forward button in the browser.
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:
The window.navigator object contains information about the visitor's browser.
The window.navigator object can be written without the window prefix.
Some examples:
The cookieEnabled property returns true if cookies are enabled, otherwise false:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"cookiesEnabled is " + navigator.cookieEnabled;
</script>
Try it Yourself »
The appName property returns the application name of the browser:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"navigator.appName is " + navigator.appName;
</script>
Try it Yourself »
Strange enough, "Netscape" is the application name for both IE11, Chrome, Firefox, and Safari.
The appCodeName property returns the application code name of the browser:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"navigator.appCodeName is " + navigator.appCodeName;
</script>
Try it Yourself »
"Mozilla" is the application code name for both Chrome, Firefox, IE, Safari, and Opera.
The product property returns the product name of the browser engine:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"navigator.product is " + navigator.product;
</script>
Try it Yourself »
Do not rely on this. Most browsers returns "Gecko" as product name !!
The appVersion property returns version information about the browser:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.appVersion;
</script>
Try it Yourself »
The userAgent property returns the user-agent header sent by the browser to the server:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.userAgent;
</script>
Try it Yourself »
The information from the navigator object can often be misleading, and should not be used to detect browser versions because:
The platform property returns the browser platform (operating system):
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.platform;
</script>
Try it Yourself »
The language property returns the browser's language:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.language;
</script>
Try it Yourself »
The onLine property returns true if the browser is online:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.onLine;
</script>
Try it Yourself »
The javaEnabled() method returns true if Java is enabled:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.javaEnabled();
</script>
Try it Yourself »
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt 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.
window.alert("sometext");
The window.alert() method can be written without the window prefix.
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.
window.confirm("sometext");
The window.confirm() method can be written without the window prefix.
if (confirm("Press a button!") == true) {
txt = "You
pressed OK!";
} else {
txt = "You pressed Cancel!";
}
Try it Yourself »
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.
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.
var person = prompt("Please enter your name", "Harry Potter");
if
(person == null || person == "") {
txt = "User cancelled
the prompt.";
} else {
txt = "Hello " + person + "!
How are you today?";
}
Try it Yourself »
To display line breaks inside a popup box, use a back-slash followed by the character n.
1
2
3
4
5
6
7
8
9
10
11
12
|
JavaScript can be executed in time-intervals. This is called timing events. |
The window object allows execution of code at specified time intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:
The setTimeout() and setInterval() are both methods of the HTML DOM Window object.
window.setTimeout(function, milliseconds);
The window.setTimeout() method can be written without the window prefix.
The first parameter is a function to be executed.
The second parameter indicates the number of milliseconds before execution.
Click a button. Wait 3 seconds, and the page will alert "Hello":
<button onclick="setTimeout(myFunction, 3000)">Try it</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
Try it Yourself »
The clearTimeout() method stops the execution of the function specified in setTimeout().
window.clearTimeout(timeoutVariable)
The window.clearTimeout() method can be written without the window prefix.
The clearTimeout() method uses the variable returned from setTimeout():
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);
If the function has not already been executed, you can stop the execution by calling the clearTimeout() method:
Same example as above, but with an added "Stop" button:
<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>
<button onclick="clearTimeout(myVar)">Stop it</button>
Try it Yourself »
The setInterval() method repeats a given function at every given time-interval.
window.setInterval(function, milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter is the function to be executed.
The second parameter indicates the length of the time-interval between each execution.
This example executes a function called "myTimer" once every second (like a digital watch).
Display the current time:
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
Try it Yourself »
There are 1000 milliseconds in one second.
The clearInterval() method stops the executions of the function specified in the setInterval() method.
window.clearInterval(timerVariable)
The window.clearInterval() method can be written without the window prefix.
The clearInterval() method uses the variable returned from setInterval():
myVar = setInterval(function, milliseconds);
clearInterval(myVar);
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(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
Try it Yourself »
A clock created with a timing event
Cookies let you store user information in web pages.
Note that Chrome does not allow writing cookies by local files, so, server will be used to bypase it!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":
Cookies are saved in name-value pairs like:
username = John Doe
When a browser requests 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.
None of the examples below will work if your browser has local cookies support turned off.
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=/";
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;
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.
Deleting a cookie is very simple.
You don't have to specify a cookie value when you delete a cookie.
Just set the expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01
Jan 1970 00:00:00 UTC; path=/;";
You should define the cookie path to ensure that you delete the right cookie.
Some browsers will not let you delete a cookie if you don't specify the path.
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.
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:
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 + ";path=/";
}
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.
Then, we create a function that returns the value of a specified cookie:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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) == 0) {
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 + "=").
Decode the cookie string, to handle cookies with special characters, e.g. '$'
Split document.cookie on semicolons into an array called ca (ca = decodedCookie.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 "".
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);
}
}
}
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 + ";path=/";
}
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)
== 0) {
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.