Categories:

JavaScript Kit > JavaScript Reference > Here

Window Object

Last updated: May 20th, 2014

The Window object is the top level object in JavaScript, and contains in itself several other objects, such as "document", "history" etc.

Related Tutorials

Events

Events Description
onblur Fires when the window loses focus.
onerror Fires when a JavaScript error occurs. By returning true inside this event, JavaScript errors on the page (if any) are suppressed, with no error messages popping up:

window.onerror=function(msg, url, linenumber){
 var logerror='Error message: ' + msg + '. Url: ' + url + 'Line Number: ' + linenumber
 alert(logerror)
 return true
}

See "The onerror event of the window object" for full details.

onfocus Fires when the focus is set on the current window.
onload Fires when the page has finished loading, including images. This is a popular event to use to run some JavaScript once everything on the page has loaded/ is available:

window.onload=function(){
 runsomefunction()
}

The limitation with the above approach is that multiple calls to window.onload on the same page causes all but the last one to be adopted, with each proceeding call overwritten by the one following it. On a page with multiple JavaScripts, this is more likely than not to happen. To overcome this, you can invoke the onload event handler using the DOM methods element.addEventListener() and its counterpart element.attachEvent() in IE. Event handlers defined in this manner will not get overwritten by their counterparts, but instead queued.

onresize Fires when the window is resized.
onscroll Fires when the window is scrolled. The following shows the current y coordinate of the upper left corner of the viewable window in the browser's title bar when the page is scrolled:

window.onscroll=function(){
 var scrollY=window.pageYOffset || document.body.scrollTop
 document.title=scrollY
}

onbeforeunload Fires when the page is about to be unloaded, prior to window.onunload event firing. Supported in all modern browsers. By setting event.returnValue to a string, the browser will prompt the user whether he/she wants to leave the current page when attempting to:

window.onbeforeunload=function(e){
 e.returnValue="Any return string here forces a dialog to appear when user leaves this page"
}

window.location="http://www.google.com" //prompt is invoked

onunload Fires when the page is unloaded- process cannot be overruled at this point. Often used to run code cleanup routines.

Properties

Properties Description
closed Returns the Boolean variable indicating whether window has been closed or not. Also see: "Determining whether a browser window is open or not".
defaultStatus Read/write property that reflects the default window status bar message that appears.
document Reference to the current document object.
frames An array referencing all of the frames in the current window, including IFRAME elements. Use frames.length to probe the number of frames. The following changes the src property of every IFRAME on the page to a blank page:

<iframe src="http://google.com"></iframe>
<iframe src="http://yahoo.com"></iframe>

<script type="text/javascript">

for (var i=0; i<frames.length; i++){
 frames[i].location="about:blank"
}

</script>

If the current page is contained in a frame itself and you wish to access another sibling frame, navigate up towards the topmost frameset document first using the parent property of window, for example:

parent.frames[0] //access first frame within parent frameset.

history Reference to the History object of JavaScript, which contains information on the URLs the visitor has visited within the window.
innerWidth, innerHeight

- Supported in: Firefox/Opera/Safari, but NOT IE.

Returns the width and height, in pixels, of the window's viewable content area, which does not include any toolbar, scrollbars etc.

Note: IE equivalents are "document.body.clientWidth" and "document.body.clientHeight"

outerWidth, outerHeight

- Supported in: Firefox/Opera/Safari, but NOT IE.

Returns the width and height, in pixels, of the browser window in its entirety, which includes any toolbar, scrollbars etc. No IE equivalents.
length Returns the number of frames contained in the window, which includes IFRAMEs.
location Returns or sets the location object of JavaScript, which contains information on the current URL.
name The name of the window as optionally specified when calling window.open().
opener Contains a reference to the window that opened the secondary window via window.open(). This property should be invoked in the secondary window. See "Creating window remotes using the window.opener property".
parent Reference to the parent frameset window of the current window, assuming current window is a frame. Otherwise, it simply refers to current window.
self A synonym for the current window.
status A read/write property that allows you to probe and write to the browser's status bar.
top A synonym for the topmost browser window.
window References the current window. Same as "self."
pageXOffset, pageYOffset

- Supported in: Firefox/Opera/Safari, but NOT IE.

Returns an integer representing the pixels the current document has been scrolled from the upper left corner of the window, horizontally and vertically, respectively. You can also use window.scrollX and window.scrollY instead for brevity, which are equivalent properties.

Note: IE+ equivalents are "document.body.scrollLeft" and "document.body.scrollTop"

screenX, screenY

- Supported in: Firefox/Opera/Safari, but NOT IE.

Specifies the x and y coordinates of the window relative to the user's monitor screen.

Note: IE+ equivalents are "window.screenLeft" and "window.screenTop"

screenLeft, screenTop

- IE only properties

Specifies the x and y coordinates of the window relative to the user's monitor screen.

Methods

Note: "[]" surrounding a parameter below means the parameter is optional.

Methods Description
alert(msg) Displays an Alert dialog box with the desired message and OK button.
blur() Removes focus from the window in question, sending the window to the background on the user's desktop.
cancelAnimationFrame(ID)

- IE10+, FF11+, Chrome and Safari 6+

Cancels an animation frame request set using ID=requestAnimationFrame(). The following creates a "universal" requestAnimationFrame method based on the supported vendor prefixed version of your browser:

window.cancelAnimationFrame = window.cancelAnimationFrame
                              || window.mozCancelAnimationFrame
                              || function(requestID){clearTimeout(requestID)} //fall back to clearing a setTimeout requestID

Note: Older versions of Mozilla supported a prefixed version of cancelAnimationFrame(). All other relevant browsers starting supporting the unprefixed version from the beginning.

clearInterval(ID) Clears the timer set using var ID=setInterval().
clearTimeout(ID) Clears the timer set using var ID=setTimeout().
close() Closes a window.
confirm(msg) Displays a Confirm dialog box with the specified message and OK and Cancel buttons. Returns either true or false, depending on which button the user has clicked on, for example:

var yourstate=window.confirm("Are you sure you are ok?")
if (yourstate) //Boolean variable. Sets to true if user pressed "OK" versus "Cancel."
 window.alert("Good!")

find(string, [casesensitive], [backward])

- Firefox only property

Searches for the "string" within the page, and returns string or false, accordingly. "casesensitive" is a Boolean denoting whether search is case sensitive. "backwards" is a Boolean when set to true, searches the page backwards. Final two optional parameters must be set together or none at all.
focus() Sets focus to the window, bringing it to the forefront on the desktop.
home()

- Firefox only property

Navigates the window to the homepage as designated by the user's browser setting.
moveBy(dx, dy) Moves a window by the specified amount in pixels.
moveTo(x, y) Moves a window to the specified coordinate values, in pixels. The following opens a window and centers it on the user's screen:

Demo: Open Window

<script type="text/javascript">

function centeropen(url, winwidth, winheight){
 var centerwin=window.open(url, "", "toolbar=1, resize=1, scrollbars=1, status=1")
 centerwin.resizeTo(winwidth, winheight)
 centerwin.moveTo(screen.width/2-winwidth/2, screen.height/2-winheight/2) //center window on user's screen
}

</script>


<a href="#" onClick="centeropen('about:blank', 800, 650); return false">Open Window</a>

open(URL, [name], [features], [replace]) Opens a new browser window. "Name" argument specifies a name that you can use in the target attribute of your <a> tag. "Features" allows you to show/hide various aspects of the window interface (more info). "Replace" is a Boolean argument that denotes whether the URL loaded into the new window should add to the window's history list.

window.open("http://www.dynamicdrive.com", "", "width=800px, height=600px, resizable")

When defining the features (3rd parameter), separate each feature with a comma (,).

Restriction: In IE, an exception is thrown if you try to open a window containing a page from another domain and then try to manipulate that window. For example:

var mywin=window.open("http://www.notcurrentdomain.com", "", "width=800px, height=600px, resizable")
mywin.moveTo(0, 0) //Not allowed in IE: an exception is thrown.

This restriction does not apply in other browsers.

print() Prints the contents of the window or frame.
prompt(msg, [input]) Displays a Prompt dialog box with a message. Optional "input" argument allows you to specify the default input (response) that gets entered into the dialog box. This function returns the string the user has entered:

var yourname=window.prompt("please enter your name")
 alert(yourname)

requestAnimationFrame(func)

- IE10+, FF11+, Chrome and Safari 6+

Executes any function passed into it on the next available screen repaint by the browser. Unlike setTimeout() that executes a function after a user defined delay, requestAnimationFrame  executes that function automatically as soon as the browser reports it's ready for the next screen repaint. The following creates a "universal" requestAnimationFrame method based on the supported vendor prefixed version of your browser:

window.requestAnimationFrame = window.requestAnimationFrame
                               || window.mozRequestAnimationFrame
                               || window.webkitRequestAnimationFrame
                               || window.msRequestAnimationFrame
                               || function(f){return setTimeout(f, 1000/60)} //fall back method, run roughly 60 times per second

When requestAnimationFrame is called recursively, such as inside the function we pass into it, it behaves a lot like setInterval, except it repeats itself not based on the user defined interval, but again, at every next available screen repaint. Based on the typical screen refresh rate of 60 frames per second, a recursively called requestAnimationFrame would then be executed around 60 times per second.

requestAnimationFrame is an attractive replacement to setInterval for animating objects on the screen frame by frame, as it intelligently decides when to repeat itself based on the screen's readiness to repaint the screen. With setInterval, the user defined interval becomes meaningless, even counter efficient as constant changes in available system resources lead to frame skipping and layout thrashing.

requestAnimationFrame returns an unique ID you can use to cancel the next operation, using cancelAnimationFrame(ID).

The callback function entered into requestAnimationFrame(func) carries a single timestamp parameter that contains the current time in the form of milliseconds when the method was invoked. The following uses requestAnimationFrame to animate a DIV across the screen for the desired distance over the desired duration:

var myblock = document.getElementById("square")

var starttime = 0

function moveit(timestamp, el, dist, duration){
 if (typeof timestamp == 'undefined'){ //if  browsers don't support requestAnimationFrame, generate our own timestamp
  var timestamp = new Date().getTime()
 }
 if (starttime === 0){ //first time running requestAnimationFrame?
  starttime = timestamp
 }
 var runtime = timestamp - starttime
 var progress = runtime / duration
 progress = Math.min(progress, 1)
 el.style.left = (dist * progress).toFixed(2) + 'px'
 if (runtime < duration){ // if duration not met yet
  requestAnimationFrame(function(timestamp){ // call requestAnimationFrame again with parameters
   moveit(timestamp, el, dist, duration)
  })
 }
}

requestAnimationFrame(function(timestamp){
 moveit(timestamp, myblock, 400, 1000) // 400px over 1 second
})

Demo:


Run Demo

resizeBy(dx, dy) Resizes a window by the specified amount in pixels.
resizeTo(x y) Resizes a window to the specified pixel values. The following will resize the current window to be maximized on the screen in browsers with no security hang ups over such an operation (IE does and will do nothing):

window.resizeTo(screen.availWidth, screen.availHeight) //see also the screen object

scrollBy(dx, dy) Scrolls a window by the specified amount in pixels.
scrollTo(x, y) Scrolls a window to the specified pixel values.
setInterval(func, interval, [args]) Calls the specified function reference (func) or JavaScript statement(s) repeatedly per the "interval" parameter, in milliseconds (ie: 1000=every 1 second). This method returns a unique ID which can be passed into clearInterval(id) to clear the timer. Use the optional "args" to pass any number of arguments to the function. The following are all valid examples of setInterval():

setInterval(myfunction, 5000) //function reference

var timer=setInterval("document.title='Current Second: ' + new Date().getSeconds()", 1000) //statements should be surrounded in quotes)

If you need to repeated call a function that accepts parameters, put that function inside an anonymous function:

setInterval(function(){myfunction(param)}, 5000)

setTimeout("func", interval, [args]) Calls the specified function reference (func) or JavaScript statement(s) once after the "interval" parameter has expired, in milliseconds (ie: 1000=after 1 second). This method returns a unique ID which can be passed into clearTimeout(id) to clear the timer.
stop() Stops the window from loading. NS4/NS6+ exclusive method. Use the optional "args" to pass any number of arguments to the function.

Window Features in window.open()

The below lists the string features you can pass into the "feature" parameter of window.open() to manipulate its interface. Most features support a value of true or false, though in general, simply including the name of the feature implies it should be added to the window (yes), while not including it means it shouldn't (no). Separate each feature with a comma (,).

Feature Description
channelmode Specifies if window should be opened in channel mode. IE only.
fullscreen Specifies if window should be opened in full screen mode. IE only.
height Specifies the height of the window.
left Specifies the x coordinates of the window in pixels. IE only. See "screenX" as well.
location Specifies if the location bar of the window should be included.
menubar Specifies if the menu bar of the window should be included.
resizable Specifies if window should be resizable.
screenX Specifies the x coordinates of the window in pixels. NS only. See "left" as well.
screenY Specifies the x coordinates of the window in pixels. NS only. See "top" as well.
scrollbars Specifies if window should contain scrollbars.
status Specifies if the status bar of the window should be included.
toolbar Specifies if the toolbar of the window (ie: reload button) should be included.
top Specifies the y coordinates of the window in pixels. IE only. See "screenY" as well.
width Specifies the width of the window.

Reference List

Right column

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info