Making A New Window With JavaScript
2023-06-12
Making a new window open with JavaScript is fairly simple. In fact, it
only requires one command:
window.open("https://example.com"). This will likely open a
new tab. If you would like to open a new window, customize its
dimensions and attributes the .open() function takes
several parameters as well.
Here is a quick example of how I used window.open() in one
of my projects.
The Code
function openTagWindow(tag) {
// Opens a new window for user to add more tags
let params = `width=800, height=400, menubar=no, toolbar=no, left=100, top=100`
window.open('/users/add-' + tag, 'Add tags', params);
}
In an effort to DRY my code, I made a function to open a new window that
takes an argument that will direct it to open a specific page. One of
the first things I needed to figure out about the
window.open() function is that if the window size is not
specified, a new tab will be opened instead of a new window. For my use
case, I wanted a new window to open, so the first two items in the
params variable are to set the window dimensions.
The rest of the items that make up the params variable are
straightforward. They remove the menubar and toolbar, and finally
specify where the window opens. In my case I designated it to open 100
pixels down and to the right from the top left corner.
Thanks for reading!