JavaScript  

Document Object and Window Object in Java Script

Introduction

JavaScript is a powerful scripting language that enables developers to create dynamic and interactive web pages. To interact with web content, JavaScript relies on the Browser Object Model (BOM) and the Document Object Model (DOM). Two of the most important objects in this environment are the Window Object and the Document Object. These objects provide the foundation for controlling the browser window and manipulating the content inside a web page.

In this article, I will explore the Window Object and the Document Object, their roles, methods, and how they interact with each other.

Document Object

This object allows you to change the contents of the document dynamically. This object has several properties, which you can use to modify the contents of the Web page.

Properties of Document Object

PropertyDescription
alinkColorSpecifies the color of the link
AnchorsRefers to all anchors contained in a document
AppletRefers to an applet that is embedded in the current document.
AppletsRefers to an array of all applets embedded in the current document.
AreaRefers to an image map area contained in a document.
bgColorRefers to bgColor attribute of the <body>tag
CookieRefers to a string value containing name=value pairs of data that will persist in the clients memory until the browser is cleared (if no expiration date is present) or until the expiration is reached.
DomainRefers to the domain name of the server, which supplies the document
fgColorRefers to fgColor attribute of the <body>tag.
formRefers to a form contained in a document.
FormsRefers to an array of all forms contained in a document.
HistoryRefers to a list of URLs that have been visited in a window.
imageRefers to an image contained in a document.
ImagesRefers to array of images contained in a document.
lastModifiedRefers to the date on which a document was a last modified.
LinkRefers to a link contained in a document
LinksRefers to an array of all links contained in a document.
linkColorRefers to color of the link attribute of the <body> tag.
PluginRefers to plugin contained in a document
ReferrerRefers to URL of a document that provides the link to a document.
TitleRefers to the title of the document.
URLRefers to the URL of a document
vlinkColorRefers to the color of a vlink attribute of the <body> tag.

Source Code

  
    <html>
<head>
    <title>Document Object Example</title>
    <script>
        function changeContent() {
            document.getElementById("demo").innerHTML = "Hello, the content has been changed dynamically!";
            document.body.style.backgroundColor = "lightyellow";      
            let para = document.createElement("p");
            para.innerText = "This paragraph is added using the Document Object.";
            document.body.appendChild(para);
        }
    </script>
</head>
<body>
    <h2>Document Object Example in JavaScript</h2>
    <p id="demo">This is the original text.</p>
    <button onclick="changeContent()">Click Me</button>
</body>
</html>
  

Output

fig1!fig2!

In the above example, the Document Object is used to dynamically modify the content of a web page. Initially, the paragraph with the id demo displays the text This is the original text. When the user clicks on the Click Me button, the JavaScript function changeContent() is executed. Inside this function, the document.getElementById(demo).innerHTML statement changes the text of the paragraph. Next, the background color of the entire page is modified using document.body.style.backgroundColor. Finally, a new paragraph element is created with document.createElement(p), and it is added to the page using document.body.appendChild(para). This demonstrates how the Document Object allows developers to access, modify, and add HTML elements dynamically.

Window Object

The Window Object is the top-level object in the browser's JavaScript hierarchy. It represents the browser window or tab in which a web page is loaded. Every global variable, function, or object created in JavaScript automatically becomes a property of the Window Object.

This object is a top level object in the JavaScript object model. It is a predefined object for which there is no need for declaration. Every window opened by the browser, which supports JavaScript defines a separate window object for the window. When use the statement

  
    document.write("this is Hello from JavaScript")
  

is actually expanded by the JavaScript  interpreter as

  
    window.document.write("this is Hello from JavaScript")
  

The Window object has several synonyms that can be used to access the browser windows, which are implemented as properties of the window object. The following tables describe all properties and methods of the window object.

Properties ofthe Window Object

PropertyDescription
ClosedChecks if a window is closed.
DefaultStatusIdentifies the default status bar message.
DocumentRefers to a document being displayed in a window.
FrameRefers to a single frame.
FramesRefers to an array consisting of all frame objects within a frameset or window.
LengthRefers to the total number of frames contained in a frameset or window
LocationRefers to a URL of a window
NameRefers to the name of the window
OpenerIdentifies the window object that causes a window object.
ParentRefers to a window that is at one level above the current window.
SelfRefers to the current window.
StatusRefers to a temporary message appearing on the status bar.
TopRefers to a top-level window in a series of windows.
WindowRefers to the current window.

Methods of Wthe indow Object

MethodDescription
alert(text)Display an alert box
Blur()Removes focus from the window.
ClearTimeout(timer)Clears a predefined timeout.
close()Closes the specified window.
confirm(text)Display a confirm dialog box
focus()Gives focus to a window.
open(url,name,[options])Creates a window object and opens a new window.
prompt(text,defaultInput)Display a prompt dialog box
scroll(x,y)Scrolls a window to the specified location
setTimeout(expression, milliseconds)Executes an expression after timeout period elaspses.
clearInterval(ID)Clears a timeout created by setInterval()
moveBy(horz,vert)Moves the window by a specified amount.
moveTo(x,y)Moves to the specified location.
resizeBy(horz,vert)Resizes the window by moving the bottom right corner
resizeTo(width, height)Resizes the window by the specified dimensions.
scrollBy(horz,vert)Scroll the Window
scrollTo(x,y)Scroll to specific position
setInterval(function, time,[args])Repeatedly invokes a function or evaluates an expression after a timeout (in milliseconds) expires.
setTimeOut(function, time, [args])Executes a function after a timeout (in milliseconds) expires.

Source Code

  
    <html>
<head>
    <title>Window Object Example</title>
    <script>
        function showWindowFeatures() {
            window.alert("Hello! This is an alert from the Window Object.");
            document.getElementById("size").innerHTML = 
                "Window Width: " + window.innerWidth + "px, Height: " + window.innerHeight + "px";
            window.setTimeout(function() {
                document.getElementById("message").innerHTML = "This message appears after 3 seconds!";
            }, 3000);
        }
    </script>
</head>
<body>
    <h2>Window Object Example in JavaScript</h2>
    <p id="size">Click the button to see window size.</p>
    <p id="message"></p>
    <button onclick="showWindowFeatures()">Click Me</button>
</body>
</html>
  

Output

fig3!fig4!

fig5!

In this example, the Window Object is used to demonstrate some of its common methods and properties. When the user clicks on the Click Me button, the function showWindowFeatures() is executed. Inside this function, window.alert() displays a popup alert message. Then, window.innerWidth and window.innerHeight are used to show the size of the browser window, and the result is displayed inside the paragraph with the id "size". Finally, the method window.setTimeout() is used to display a new message inside the paragraph with the id "message" after a delay of 3 seconds. This shows how the Window Object allows interaction with the browser window and provides useful methods for dynamic behavior.

Key Differences Between Window and Document Objects.

Window ObjectDocument Object
Represents the browser window/tab.Represents the web page loaded in the window.
Top-level object.Child object of the window.
Global scope (functions/variables attach here).DOM scope (manipulates HTML content).
alert(), setTimeout(), open().getElementById(), querySelector(), write().

Summary

Both the Window Object and the Document Object play a vital role in client-side JavaScript programming. The Window Object gives control over the browser window and global properties, while the Document Object allows direct manipulation of the HTML and CSS within the page. Together, they provide developers with powerful tools to create dynamic, interactive, and user-friendly web applications.