In this section, we will learn what the Window moveBy() method is and how to use it in JavaScript.
JavaScript Window moveBy() Method
The moveBy() method gives us the ability to change the position of browser’s window from one position to another.
Here’s the difference between the `moveTo()` and `moveBy()` methods:
- The `moveTo()` method’s starting location (0,0) is the top left corner of the screen and values are according to this point.
- But the `moveBy()` method changes the location of the window from its current location. So basically the (0, 0) coordination means the current location of the window and not top left corner of the screen.
JavaScript Window moveBy() Syntax:
window.moveBy(x, y)
Window moveBy() Method Parameter:
The method takes two arguments:
- The first argument declares how many CSS pixels the window should move horizontally toward left or right side of the screen. If the value we set here is a negative value, the window will be moved towards the left side of the screen. But if the value is positive, the window will be moved toward the right side of the screen.
- The second argument specifies how many CSS pixels the window should move vertically. If we set a negative value, that means the location of the window is toward upside of the screen. But if the value is positive, it means the window’s location is toward downside of the screen.
Window moveBy() Method Return Value:
This method does not return a value.
Example: using Window moveBy() method in JavaScript
<!DOCTYPE html> <html> <head> <title>JS is fun :)</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h3>Output:</h3> <p id = "link"></p> <script> let winx = window.open(String.raw`F:\jScript-Work-Station\example.html`, "window", "height=400,width=400,top=30,left=30,resizable=yes"); </script> </body> </html>
The second file:
<!DOCTYPE html> <html> <head> <title>JS is fun :)</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <script> var x = 10, y = 10; setTimeout(()=>{ setInterval(()=>moveBy(x++,y++),300); },3000); </script> </body> </html>