How To Close Popup Window Automatically After Few Seconds in JavaScript

In this post, I will show you how to close popup window in JavaScript after few seconds automatically.

In some cases, it has been found that we need to close the popup window automatically without any further the user activity. So here you can find out how to close popup window automatically with JavaScript.

I will use the following things to do this:

  1. window.open() function
  2. setTimeout() function
  3. close() method

For this tutorial, I am going to create a button to open a popup window and a JavaScript function to close that window after few seconds automatically.

Also Read,

How To Add Browser Notification Using JavaScript

Popup notification using JavaScript and CSS that will hide after a certain time

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <title>Close popup window</title>
</head>
<body>
  <input type="submit" onclick="new_popup()">


</body>
</html>

Close popup window in JavaScript automatically after few seconds

here is the JavaScript function:

	<script type="text/javascript">
function new_popup(){
    var popupwin = window.open('http://www.google.com','anyname','width=10,height=1,left=5,top=3');
    setTimeout(function() { popupwin.close();}, 5000);
}
</script>

I have used 5000 milliseconds to close the popup window after 5 seconds automatically. You can modify it as per your requirement.

So the entire code is provided below:

<!DOCTYPE html>
<html>
<head>
  <title>Close popup window</title>
</head>
<body>
  <input type="submit" onclick="new_popup()">
  <script type="text/javascript">
function new_popup(){
    var popupwin = window.open('http://www.google.com','anyname','width=10,height=1,left=5,top=3');
    setTimeout(function() { popupwin.close();}, 5000);
}
</script>

</body>
</html>

Special Notes: The ‘anyname’ is used as a window name but the latest versions of browsers generally do not show the window name. Moreover, the rest of the parameters are for the position of the focus area of the popup window.

How to Hide Cursor In JavaScript or CSS very Easily

How to Create A Countdown Timer with Progress Bar in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *