How to move window using JavaScript?
JavaScript allow you to move the window either relatively or absolutely.
Window methods: These are the following window methods:
- MoveBy (dx, dy)
- MoveTo(x, y)
MoveBy() method: This method is used to move a window by a specified amount of pixels.
For Example: I am taking a simple example to explain the window method. Through this example you will see how the window shakes.
<html>
<head>
<title>Window Shake</title>
<script type="text/javascript">
function sw()
{
var x=10
if (document.all||document.layers)
{
for (i=0;i,i<5;i++)
{
window.moveBy(0,x)
window.moveBy(x,0)
window.moveBy(0,-x)
window.moveBy(-x,0)
}
}
}
</script>
</head>
<body>
<input type="button" onClick="sw()" value="Shake Window">
</body>
</html>
The moveBy() method 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 5 times.
An "earthquake" on the window is produced.
MoveTo() method: This method is used to Moves the window to the specified pixel value (coordinate on the screen).
For Example: How to move the window to upper left corner? You will see the following example to move the window at specific coordinate on the screen.
<html>
<head>
<title>Window moving</title>
<script type="text/javascript">
function open_and_move()
{
window=window.open("HTMLPage.htm","","width=200,height=200")
window.moveTo(0,0)
}
</script>
</head>
<body bgcolor= "#ffcc99">
<input type="button" onClick="open_and_move()" value="Move">
Click here to move the window to top left corner.
</body>
</html>
Output: Output of this script is as follows:
Figure 1: Output of the script.
When you click on 'Move' button then the new window will open something like this:
Figure 2: New window move to top left corner.