Functions
- What is a function?
- Pre-defined functions
- Scope of Variables
- Function Expressions
- Anonymous Functions
- Callback Functions
Objects
- What is an object?
- Accessing Object Properties
- Calling an Object’s Methods
- Altering Properties/Methods
Array Properties and Methods
- The length property
- Stack Methods
- Queue Methods
- Reordering Methods
- Manipulation Methods
- Location Methods
- Iterative Methods
- Working with array of objects
DOM
- The Document Object Model
- Node Relationships
- Working with the Contents of Elements
- Getting Elements by ID, Tag Name, or Class
- Adding and removing element
Built-in Objects
Using Events in JavaScript
Handling Input and Output
Ajax and JSON
BOM (Browser Object Model)
The BOM (Browser Object Model) is a collection of objects that give you access to the browser and the computer screen. These objects are accessible through the global objects window and window.screen.
The window object revisited
As you know already, in JavaScript there’s a global object provided by every host environment. In the browser environment, this is the window object. All global variables become properties of the window object.
window.somevar = 1;
//1
somevar;
//1
Also, all of the core JavaScript functions are methods of the window object.
parseInt('123a456');
//123
window.parseInt('123a456');
//123
In addition to being the global object, the window object also serves a second purpose and that is to provide data about the browser environment. There’s a window object for every frame, iframe, popup, or browser tab.
Let’s see some of the browser-related properties of the window object. Again, these can vary from one browser to another, so we’ll only bother with those properties that are implemented consistently and reliably across all modern browsers.
window.navigator
The navigator is an object that has some information about the browser and its capabilities. One property is navigator.userAgent, which is a long string of browser identification. In Firefox, you’ll get something like this:
window.navigator.userAgent
//"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12"
The userAgent string in Microsoft Internet Explorer would be something like:
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"
Because the browsers have different capabilities, developers have been using the userAgent string to identify the browser and provide different versions of the code. For example, this code searches for the presence of the string MSIE to identify Internet Explorer:
if (navigator.userAgent.indexOf('MSIE') !== -1) {
// this is IE
} else {
// not IE
}
It is better not to rely on the user agent string, but to use feature sniffing (also called capabilities detection). The reason for this is that it’s hard to keep track of all browsers and their different versions. It’s much easier to simply check if the feature you intend to use is indeed available in the user’s browser. For example:
if (typeof window.addEventListener === 'function') {
// feature is supported, let's use it
} else {
// hmm, this feature is not supported, will have to think of another way
}
Another reason to avoid user agent sniffing is that some browsers allow users to modify the string and pretend they are using a different browser.
window.location
The location property points to an object that contains information about the URL of the currently loaded page. For example, location.href, is the full URL and location.hostname is only the domain. With a simple loop, you can see the full list of properties of the location object. Imagine you’re on a page with a URL like this:
"http://search.phpied.com:8080/search?p=javascript#results"
for(var i in location) {console.log(i + ' = "' + location[i] + '"')}
href = "http://search.phpied.com:8080/search?p=javascript#results"
hash = "#results"
host = "search.phpied.com:8080"
hostname = "search.phpied.com"
pathname = "/search"
port = "8080"
protocol = "http:"
search = "?p=javascript"
There are also three methods that location provides—reload(), assign(), and replace().
It’s interesting to note how many different ways exist for you to navigate to another page. Here’s a partial list:
window.location.href = 'http://www.packtpub.com'
location.href = 'http://www.packtpub.com'
location = 'http://www.packtpub.com'
location.assign('http://www.packtpub.com')
replace() is almost the same as assign().
The difference is that it doesn’t create an entry in the browser’s history list:
location.replace('http://www.yahoo.com');
To reload a page you can use:
location.reload();
Alternatively, you can use location.href to point it to itself, like so:
window.location.href = window.location.href
Or simply:
location = location
window.screen
screen provides information about the desktop outside the browser. The screen.colorDepth property contains the color bit-depth (the color quality) of the monitor. This could be useful for statistical purposes.
window.screen.colorDepth
//32
You can also check the available screen real estate (the resolution):
screen.width;
//1440
screen.availWidth
//1440
screen.height
//900
screen.availHeight
//847
The difference between height and availHeight is that the height is the total resolution, while availHeight subtracts any operating system menus such as the Windows task bar. The same is the case for width and availWidth.
window.open()/close()
Having explored some of the most common cross-browser properties of the window object, let’s move to some of the methods. One such method is open(), which allows you to open up new browser windows (popups). Various browser policies and user settings may prevent you from opening a popup (due to abuse of the technique for marketing purposes), but generally you should be able to open a new window if it was initiated by the user. Otherwise, if you try to open a popup as the page loads, it will most likely be blocked, because the user didn’t initiate it explicitly.
window.open() accepts the following parameters:
- URL to load in the new window
- Name of the new window, which can be used as the value of a form’s
- target attribute
Comma-separated list of features, such as:
- resizable—should the user be able to resize the new window width, height of the popup.
- status—should the status bar be visible and so on.
window.open() returns a reference to the window object of the newly created browser instance. Here’s an example:
var win = window.open('http://www.packtpub.com', 'packt', 'width=300,height=300,resizable=yes');
win points to the window object of the popup. You can check if win has a falsy value, which means that the popup was blocked. win.close() closes the new window.
It’s best to stay away from opening new windows for accessibility and usability reasons. If you don’t like sites to pop-up windows to you, why would do it to your users? There may be legitimate purposes, such as providing help information while filling out a form, but often the same can be achieved with alternative solutions, such as using a floating <div> inside the page.
window.alert(), window.prompt(), window.confirm()
We came across the function alert(). Now you know that global functions are methods of the global object so alert(‘Watch out!’) and window.alert(‘Watch out!’) are exactly the same.
Other BOM methods allow you to interact with the user through system messages:
- confirm() gives the user two options—OK and Cancel, and
- prompt() collects textual input
See how this works:
var answer = confirm('Are you cool?');
console.log(answer);
It presents you with a window similar to the following (the exact look depends on the browser and the operating system):
You’ll notice that:
Nothing gets written to the Firebug console until you close this message, this means that any JavaScript code execution freezes, waiting for the user’s answer. Clicking OK returns true, clicking Cancel or closing the message using the X icon (or the ESC key) returns false. This is handy for confirming user actions, such as:
if (confirm('Are you sure you want to delete this item?')) {
// delete
} else {
// abort
}
Make sure you provide an alternative way to confirm user actions for people who have disabled JavaScript (or for search engine spiders).
window.prompt() presents the user with a dialog to enter text.
var answer = prompt('And your name was?');
console.log(answer);
window.setTimeout(), window.setInterval()
setTimeout() and setInterval() allow for scheduling the execution of a piece of code. setTimeout() executes the given code once after a specified number of milliseconds. setInterval() executes it repeatedly after a specified number of milliseconds has passed. This will show an alert after 2 seconds (2000 milliseconds):
function boo(){alert('Boo!');}
setTimeout(boo, 2000);
//4
As you can see the function returned the integer 4, this is the ID of the timeout. You can use this ID to cancel the timeout using clearTimeout(). In the following example, if you’re quick enough, and clear the timeout before two seconds have passed, the alert will never be shown.
var id = setTimeout(boo, 2000);
clearTimeout(id
Let’s change boo() to something less intrusive:
function boo() {console.log('boo')};
Now, using setInterval() you can schedule boo() to execute every two seconds, until you cancel the scheduled execution with clearInterval().
var id = setInterval(boo, 2000);
//boo
//boo
//boo
//boo
//boo
//boo
clearInterval(id);
Note that both functions accept a pointer to a callback function as a first parameter. They can also accept a string which will be evaluated with eval() but, as you know, using eval() is not a good practice, so it should be avoided. And what if you want to pass arguments to the function? In such cases, you can just wrap the function call inside another function. The code below is valid, but not recommended:
var id = setInterval("alert('boo, boo')", 2000);
This alternative is preferred:
var id = setInterval(
function(){
alert('boo, boo')
}, 2000
);
Examples
Create an alert box.
<script>window.alert('hello');
</script>
Create a prompt box.
<script>var input = prompt('Enter your name');
</script>
Create a confirm box.
<script>window.confirm('Are you sure?');
</script>
Print “Hello World” after 5 seconds using setTimeout method.
<script>
function boo(){
console.log('Hello World');
}
setTimeout(boo, 5000);
</script>
Print “Hello World” every 2 seconds using setInterval method and stop it after 10 seconds.
<script>
var count = 0;
function boo(){
console.log('Hello World');
count++;
if(count===5){
clearInterval(id);
}
}
var id = setInterval(boo, 2000);
</script>