The Browser Object Model (BOM) is a JavaScript API that provides a way for developers to interact with the browser window and manipulate its functionality.
BOM is not a standard specification, but most browsers have implemented similar methods and properties for BOM objects.
In this blog post, we will provide you with a cheat sheet on the basics of BOM, which will help you understand its different objects and their functionalities.
1) Window Object
The most important BOM object is the window object, which is the top-level object that contains other objects such as document, location, history, navigator, and screen.
Accessing the window object
You can access the window object directly or by using the global object in JavaScript. For example:
// Accessing the window object directly let windowObj = window; // Accessing the window object via the global object let globalObj = this; // or self or globalThis
Window object properties and methods
The window object has many properties and methods that allow you to manipulate the browser window and its components. Some of the most common ones are:
window.alert(message) // displays an alert dialog with a message and an OK button. window.confirm(message) // displays a modal dialog with a message and OK and Cancel buttons. Returns true if OK is clicked, false otherwise. window.prompt(message, default) // displays a modal dialog with a message and an input field. Returns the input value if OK is clicked, null otherwise. window.open(url, name, features, replace) // opens a new browser window or tab with the specified URL, name, features, and replace flag. Returns a reference to the new window object. window.close() // closes the current browser window or tab. window.location // returns a reference to the location object that contains information about the current URL. window.history // returns a reference to the history object that allows you to navigate through the browser’s history stack. window.navigator // returns a reference to the navigator object that provides information about the browser and its capabilities. window.screen // returns a reference to the screen object that provides information about the screen on which the browser is running. window.document // returns a reference to the document object that represents the web page loaded in the browser window. window.innerWidth // returns the width of the browser window’s viewport, excluding scrollbars. window.innerHeight // returns the height of the browser window’s viewport, excluding scrollbars. window.outerWidth // returns the width of the whole browser window, including scrollbars and borders. window.outerHeight // returns the height of the whole browser window, including scrollbars and borders. window.pageXOffset // returns the number of pixels that the document has been scrolled horizontally from the left edge of the viewport. window.pageYOffset // returns the number of pixels that the document has been scrolled vertically from the top edge of the viewport. window.scrollTo(x, y) // scrolls the document to the specified horizontal and vertical coordinates relative to the top//left corner of the document. window.scrollBy(x, y) // scrolls the document by the specified horizontal and vertical distances relative to its current position. window.resizeTo(width, height) // resizes the browser window to the specified width and height in pixels. window.resizeBy(width, height) // resizes the browser window by the specified width and height in pixels relative to its current size.
2) Document object
The document object represents the web page loaded in the browser window. It is a child of the window object and the root of the DOM (Document Object Model) tree.
Accessing the document object
You can access the document object by using the window.document property or directly. For example:
// Accessing the document object via the window object let documentObj = window.document; // Accessing the document object directly let documentObj = document;
Document object properties and methods
The document object has many properties and methods that allow you to manipulate the web page and its elements. Some of the most common ones are:
document.documentElement // returns a reference to the HTML element that is the root element of the document. document.body // returns a reference to the body element that contains the content of the document. document.head // returns a reference to the head element that contains the metadata of the document. document.title // returns or sets the title of the document. document.getElementById(id) // returns a reference to the first element in the document with the specified id attribute, or null if none is found. document.getElementsByClassName(className) // returns a live HTMLCollection of all elements in the document that have the specified class attribute. document.getElementsByTagName(tagName) // returns a live HTMLCollection of all elements in the document that have the specified tag name. document.querySelector(selector) // returns a reference to the first element in the document that matches the specified CSS selector, or null if none is found. document.querySelectorAll(selector) // returns a static NodeList of all elements in the document that match the specified CSS selector. document.createElement(tagName) // creates and returns a new element with the specified tag name. document.createTextNode(text) // creates and returns a new text node with the specified text content. document.createDocumentFragment() // creates and returns a new empty document fragment, which is a lightweight container for holding DOM nodes. document.createComment(text) // creates and returns a new comment node with the specified text content. document.createAttribute(name) // creates and returns a new attribute node with the specified name. document.appendChild(child) // appends a child node to the end of the list of children of the document node. Returns the appended child node. document.removeChild(child) // removes a child node from the list of children of the document node. Returns the removed child node. document.replaceChild(newChild, oldChild) // replaces an old child node with a new child node in the list of children of the document node. Returns the replaced child node. document.insertBefore(newChild, refChild) // inserts a new child node before a reference child node in the list of children of the document node. Returns the inserted child node. If refChild is null, inserts newChild at the end of the list of children.
3) Element object
An Element object is a type of object that represents an HTML element in the Document Object Model (DOM). It has properties and methods that are common to all kinds of elements, such as id, className, innerHTML, etc.
Accessing the Element object
To access an element object in the DOM, you can use different methods of the document object. Some of the most common methods are:
getElementById () //This method takes an ID string as an argument and returns the element object with that ID, or null if no such element exists. getElementsByClassName () //This method takes a class name string as an argument and returns a collection of element objects that have that class name, or an empty collection if no such elements exist. getElementsByTagName () //This method takes a tag name string as an argument and returns a collection of element objects that have that tag name, or an empty collection if no such elements exist. querySelector () //This method takes a CSS selector string as an argument and returns the first element object that matches that selector, or null if no such element exists. querySelectorAll () //This method takes a CSS selector string as an argument and returns a collection of element objects that match that selector, or an empty collection if no such elements exist.
Element object properties and methods
To access the properties and methods of an element object, you can use the dot notation (element.property or element.method ()) or the bracket notation.
The dot notation is more concise and readable, but the bracket notation allows you to use variables and expressions as property names. For example:
// Dot notation let demo = document.getElementById ("demo"); demo.innerHTML = "Hello World!"; demo.style.color = "red"; // Bracket notation let demo = document.getElementById ("demo"); demo ["innerHTML"] = "Hello World!"; let prop = "color"; demo.style [prop] = "red";
4) Location object
A Location object is a type of object that represents the URL of the current webpage.
It has properties and methods that allow you to get or set various parts of the URL, such as the protocol, host, pathname, search, hash, etc. For example:
// location: https://example.com:8080/path/to/page?name=John#section1 console.log(location.href); // https://example.com:8080/path/to/page?name=John#section1 console.log(location.protocol); // https: console.log(location.host); // example.com:8080 console.log(location.hostname); // example.com console.log(location.port); // 8080 console.log(location.pathname); // /path/to/page console.log(location.search); // ?name=John console.log(location.hash); // #section1 console.log(location.origin); // https://example.com:8080 location.assign("https://another.site"); // load another page location.reload(); // reload the current page location.replace("https://yet.another.site"); // replace the current page with a new one
5) History object
A History object is a type of object that represents the browser’s session history for the current window. It is a property of the Window object and can be accessed with window.history or just history.
It has properties and methods that allow you to get the number of pages in the history stack, or to navigate back and forth through the user’s history, or to add or replace pages in the history stack. For example:
// get the number of pages in the history stack console.log(history.length); // 3 // go back one page (same as clicking the back button) history.back(); // go forward one page (same as clicking the forward button) history.forward(); // go to a specific page relative to the current page history.go(-2); // go back two pages history.go(1); // go forward one page history.go(0); // reload the current page // add a new page to the history stack history.pushState({page: 1}, "title 1", "?page=1"); // replace the current page in the history stack history.replaceState({page: 2}, "title 2", "?page=2");
6) Navigator object
The navigator object is a property of the window object that contains information about the browser. You can access it with window.navigator or just navigator.
Some of the properties and methods of the navigator object are:
navigator.appCodeName //returns the browser code name. navigator.appName //returns the browser name. navigator.appVersion //returns the browser version. navigator.cookieEnabled //returns true if browser cookies are enabled1. navigator.geolocation //returns a geolocation object for the user’s location1. navigator.language //returns the browser language. navigator.languages //returns an array of languages known to the user. navigator.javaEnabled() //returns true if the browser has Java enabled. navigator.mediaDevices //returns a reference to a MediaDevices object that can be used to access media devices.
7) Screen object
The screen object is a special object for inspecting properties of the screen on which the current window is being rendered. It contains information about the visitor’s screen, such as the height, width, color depth, pixel depth, etc
Some of the properties and methods of the Screen object are:
screen.width //Returns the width of the screen in pixels. screen.height //Returns the height of the screen in pixels. screen.availWidth //Returns the available width of the screen in pixels (excluding taskbars, etc.). screen.availHeight //Returns the available height of the screen in pixels (excluding taskbars, etc.). screen.colorDepth //Returns the number of bits used to display colors. screen.pixelDepth //Returns the pixel depth of the screen. screen.orientation //Returns an object that describes the orientation of the screen. screen.capture() //Captures a screenshot of the screen and returns it as a Blob object. screen.lockOrientation() //Locks the orientation of the screen to a specified mode. screen.unlockOrientation() //Unlocks the orientation of the screen. screen.orientation.lock() //Locks the orientation of the screen to a specified mode (same as lockOrientation()). screen.orientation.unlock() //Unlocks the orientation of the screen (same as unlockOrientation()).
8) Timers
Timers refer to a set of JavaScript functions that allow you to execute code after a certain amount of time has passed. These functions are a part of the BOM, and include the following:
setTimeout //Executes a function once after a specified delay. setInterval //Executes a function repeatedly at a specified interval. setImmediate //Executes a function immediately after the current event loop. requestAnimationFrame //Executes a function at the next repaint of the browser, usually at a rate of 60fps. clearTimeout //Cancels a setTimeout operation that has not yet been executed. clearInterval //Cancels a setInterval operation that has not yet been executed. clearImmediate //Cancels a setImmediate operation that has not yet been executed. cancelAnimationFrame //Cancels a requestAnimationFrame operation that has not yet been executed.
Here are some examples of how to use BOM timers in JavaScript:
function sayHello() { console.log("Hello!"); } setTimeout(sayHello, 1000); // logs "Hello!" after 1 second setInterval(sayHello, 1000); // logs "Hello!" every second setImmediate(sayHello); // logs "Hello!" immediately let timeoutID = setTimeout(sayHello, 1000); clearTimeout(timeoutID); // cancel the timeout let timeoutID = setTimeout(sayHello, 1000); clearInterval(intervalID); // cancel the interval let immediateID = setImmediate(sayHello); clearImmediate(immediateID); // cancel the immediate operation function animate() { // code to animate requestAnimationFrame(animate); } requestAnimationFrame(animate); // animate at 60fps let animationID = requestAnimationFrame(animate); cancelAnimationFrame(animationID); // cancel the animation
9) XMLHttpRequest
XMLHttpRequest is an API in the form of an object whose methods transfer data between a web browser and a web server.
It is used to perform HTTP requests and receive responses without reloading the page. It is commonly used in AJAX programming.
To create an XMLHttpRequest object, you can use the constructor syntax like this:
var xhttp = new XMLHttpRequest();
To send and receive HTTP requests, you can use the following methods of the XMLHttpRequest object:
xhttp.open(method, url, async) //This method specifies the request parameters, such as the HTTP method (GET, POST, etc.), the URL of the server, and whether the request is asynchronous or not. The default value for async is true, which means the request will not block the execution of the script12. xhttp.send(data) //This method sends the request to the server. If the request is a POST or PUT request, you can optionally provide a data parameter that contains the body of the request12. xhttp.onreadystatechange //This property is a function that is executed every time the state of the XMLHttpRequest object changes. The state can be one of the following values: 0 (uninitialized), 1 (open), 2 (sent), 3 (receiving), or 4 (done)12. xhttp.readyState //This property returns a number that represents the current state of the XMLHttpRequest object12. xhttp.status //This property returns a number that represents the HTTP status code of the response, such as 200 (OK), 404 (Not Found), etc.12. xhttp.statusText //This property returns a string that contains the HTTP status text of the response, such as “OK”, “Not Found”, etc.12. xhttp.response //This property returns the response data from the server, which can be an ArrayBuffer, a Blob, a Document, a JavaScript object, or a string, depending on the value of xhttp.responseType2. xhttp.responseText //This property returns the response data from the server as a text string12. xhttp.responseXML //This property returns the response data from the server as an XML document12. xhttp.responseType //This property specifies the type of the response data, which can be one of the following values: “” (default), “arraybuffer”, “blob”, “document”, “json”, or "text"2. xhttp.responseURL //This property returns the URL of the response or an empty string if the URL is null2.
Here is an example of how to use XMLHttpRequest to send a GET request to a server and display the response text in an HTML element with id=“demo”:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "example.txt", true); xhttp.send();
10) FormData
The FormData object provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be sent with an XMLHttpRequest. Here are some of the key methods and properties of the FormData object:
new FormData() //creates a new, empty FormData object. FormData.append(name, value) //adds a new key/value pair to the FormData object. FormData.delete(name) //removes a key/value pair from the FormData object. FormData.entries() //returns an iterator over all the key/value pairs in the FormData object. FormData.get(name) //returns the value for a given key in the FormData object. FormData.set(name, value) //sets the value for a given key in the FormData object.
Here is an example of how to use FormData to create a form with two text fields and one file field, and send it to a server using fetch:
// create an empty FormData object let formData = new FormData(); // append text fields formData.append("firstName", "John"); formData.append("lastName", "Smith"); // append a file field let fileInput = document.querySelector("input[type='file']"); let file = fileInput.files[0]; // get the selected file formData.append("picture", file, file.name); // append it to formData // send the form data to the server using fetch fetch("/article/formdata/post/user-avatar", { method: "POST", body: formData }) .then(response => response.json()) .then(result => alert(result.message)) .catch(error => console.error(error));
11) WebSocket
The WebSocket API provides a way to establish a two-way communication channel between a client and a server over a single TCP socket connection.
Here are some of the key methods and properties of the WebSocket object:
new WebSocket(url[, protocols]) //creates a new WebSocket object and initiates the connection to the server specified by the URL. Optionally, you can provide a list of protocols that the client can use to communicate with the server. WebSocket.send(data) //sends data to the server over the WebSocket connection. WebSocket.close([code[, reason]]) //closes the WebSocket connection. Optionally, you can provide a numeric status code and a string reason for the closure. WebSocket.readyState //returns the current state of the WebSocket connection. The possible values are //CONNECTING, OPEN, CLOSING, and CLOSED. WebSocket.onopen //an event handler that is called when the WebSocket connection is established. WebSocket.onmessage //an event handler that is called when a message is received over the WebSocket connection. WebSocket.onerror //an event handler that is called when an error occurs with the WebSocket connection. WebSocket.onclose //an event handler that is called when the WebSocket connection is closed.
Here is an example of how to use WebSocket to send and receive messages with a server:
// create a WebSocket object let socket = new WebSocket("ws://localhost:8080"); // handle open event socket.onopen = (event) => { console.log("Connection opened"); // send a message to the server socket.send("Hello Server!"); }; // handle message event socket.onmessage = (event) => { console.log("Message from server ", event.data); // close the connection socket.close(1000, "Work done"); }; // handle close event socket.onclose = (event) => { console.log("Connection closed", event.code, event.reason); }; // handle error event socket.onerror = (event) => { console.error("Error on connection", event); };
12) localStorage and sessionStorage
localStorage
and sessionStorage
are two objects in the web storage API that allow you to store key-value pairs in the browser.
Here are some of the methods and properties available for both objects:
localStorage.setItem(key, value) //stores a key-value pair in the localStorage object. The key and value parameters are both strings. localStorage.getItem(key) //retrieves the value associated with the specified key from the localStorage object. If the key does not exist, it returns null. localStorage.removeItem(key) //removes the key-value pair associated with the specified key from the localStorage object. localStorage.clear() //removes all key-value pairs from the localStorage object. localStorage.length //returns the number of key-value pairs stored in the localStorage object. sessionStorage.setItem(key, value) //stores a key-value pair in the sessionStorage object. The key and value parameters are both strings. sessionStorage.getItem(key) //retrieves the value associated with the specified key from the sessionStorage object. If the key does not exist, it returns null. sessionStorage.removeItem(key) //removes the key-value pair associated with the specified key from the sessionStorage object. sessionStorage.clear() //removes all key-value pairs from the sessionStorage object. sessionStorage.length //returns the number of key-value pairs stored in the sessionStorage object.
Example usage:
// Storing data in localStorage localStorage.setItem('name', 'John'); localStorage.setItem('age', 30); // Retrieving data from localStorage const name = localStorage.getItem('name'); const age = localStorage.getItem('age'); console.log(name, age); // John 30 // Removing data from localStorage localStorage.removeItem('name'); localStorage.clear(); // Storing data in sessionStorage sessionStorage.setItem('token', 'abc123'); sessionStorage.setItem('expiry', '2023-04-30'); // Retrieving data from sessionStorage const token = sessionStorage.getItem('token'); const expiry = sessionStorage.getItem('expiry'); console.log(token, expiry); // abc123 2023-04-30 // Removing data from sessionStorage sessionStorage.removeItem('token'); sessionStorage.clear();
Conclusion
The Browser Object Model, or BOM for short, is a group of objects that help web developers add extra features to their websites. Some of these objects, like the window object, let developers work with the browser window itself. For example, with the window object, developers can resize the window or open new windows. Other objects in the BOM, like the history object, let developers work with the user’s browsing history. This can be useful for creating a back button or for tracking which pages the user has visited.
In addition to objects, the BOM also includes methods for interacting with the browser. Methods are just special functions that do specific tasks. Two examples of BOM methods are the alert() and prompt() methods. The alert() method displays a message to the user, while the prompt() method lets the user enter some text. These methods are handy for creating pop-up messages or for asking the user for input.
BOM knowledge is crucial for creating dynamic websites that can interact with users, manipulate browser windows, and use browsing history. It allows developers to make web applications that resemble desktop or mobile apps, providing a better user experience.
Thank you for sharing your thoughts. I really appreciate your efforts and I
will be waiting for your further write ups thanks once again.
Hey people!!!!!
Good mood and good luck to everyone!!!!!
I dugg some of you post as I thought they were very useful very beneficial