Moving a window

JavaScript allows you to move a window either relatively (by the amount specified), or absolutely (to the coordinates on the screen specified). For your convenience, here are the related window methods again:

Methods Description
moveBy(dx, dy) Moves a window by the specified amount in pixels
moveTo(x,y) Moves a window to the specified pixel values

- moveBy() method

Use moveBy() to move a window either horizontally, vertically, or both, by the specified amount in pixels. Note that a negative parameter value causes the window to be moved in the opposite direction. Here are a couple of examples:

Example #1: Move to the Left!

<input type="button" onClick="window.moveBy(5,0)" value="Move to the right">

Example #2: Shake window

<script type="text/javascript">

function shakewindow() {
	var x=10
	if (document.all||document.layers) {
		for (i=0;i,i<20;i++){

<input type="button" onClick="shakewindow()" value="Shake Window">

Let's briefly explain the cause of the earthquake in the second example:

  • The moveBy() function is used to move the window down 10 pixels, then right, then up, and finally, left, back to the window's original position on the screen. Note where and how "x" appears in each of the four moveBy() functions.
  • A "for" loop is implemented around these moveBy() functions to execute the shaking action 20 times.
  • An "earthquake" on the window is produced!

-moveTo() method

moveTo(), as the method name implies, moves a window to the specified coordinates on the screen. Two common uses of it is to move a newly opened window to the upper left corner of the screen, and to the dead center. Let's see an example of each!

Example #3: Move to upper-left corner

<script type="text/javascript">
function open_and_move1(){"page.htm","","width=300,height=300")

Example #4: Move to center

<script type="text/javascript">
function open_and_move2(){"page.htm","","width=600,height=500")

The center coordinates of the screen in the second example is calculated by determining the screen's dimensions, dividing that by 2, and subtracting half of either the window's width/height from it. In other words, in order to center a window, it's dimensions have to be known before hand...

Let's move on, shall we?