JavaScript

How to Open a Popup Window in JavaScript Using Onclick?

Popup windows on the web page enhance the user experience. It is a handy feature of JavaScript language that is used to display additional information or features without leaving the current page. For instance, if you want to give some extra information from any other website on a button’s click, use a popup window to open the provided URL. It helps to stay the user on the same website and also access related information from external resources.

This blog will illustrate the procedure to open a popup window in JavaScript using an onclick.

How to Open a Popup Window Using onclick in JavaScript?

To open a popup window using the onclick event, use the JavaScript predefined “window.open()” method. It accepts two main parameters and many optional parameters. The “URL” and the “name” of the new window or tab is the main parameters. The other optional parameters allow adding additional features such as the position or size of the new window, whether or not it contains a status bar, toolbars, and many more.

Syntax

The following syntax is used for the “window.open()” method:

window.open(url, name, windowFeatures)

Example

First, we will create a button in an HTML file and attach an “onclick” event that will invoke the function “popup()” to open a popup window on a button click:

<button onclick = "popup()">Click Here!</button>

Now, define a function named “popup()” in <script> tag and call the “window.open()” method. Pass the “URL”, the “name” (“popUpWindow”) which represents opening the URL in a popup window, and the optional features, such as the height and width of the popup window:

function popup(){
window.open('https://linuxhint.com/', 'popUpWindow', 'height = 300, width = 500, left = 100, top = 100, scrollbars = yes, resizable = yes, menubar = no, toolbar = yes, location = no, directories = no, status = yes')
}

It can be seen that the popup window with specified URL and assigned width and height has been successfully opened:

That was all about opening a popup window in JavaScript on a button click.

Note: If you want to create a customized popup window using the “div” element to show particular information, kindly visit our dedicated article.

Conclusion

For opening a popup window, utilize the JavaScript predefined “window.open()” method. It opens a new window with the given URL. It is frequently utilized in web development to build links that open in a new window with particular information. This blog illustrated the procedure to open a popup window in JavaScript using an onclick event.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.