JavaScript: How to create alerts and pop-up windows

In JavaScript, alerts can be created easily using the built-in alert() function. For this first example, an alert is placed directly inside the button tag:

<button onclick="alert('I am an alert box!');">Example 1</button>

Here is a more complete example, showing in the HTML context:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Alert Example 1</h2>

<button onclick="alert('I am an alert box!');">Example 1</button>

</body>
</html>

For this second example, the alert is placed in a function.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Alert Example 2</h2>

<button onclick="myFunction()">Example 2</button>

<script>
function myFunction() {
    alert("Example 2: alert inside a function.");
}
</script>

</body>
</html>

This third example is how to create a pop-op window with HTML content. In this case, the HTML content must be in a document saved on the website. This uses a JavaScript function called Popup that takes in the URL of the page to open, and the width and height of the pop-up window. This example shows how to launch the pop-up window with an HREF link that points to a page about Server Side Includes.

Here is the complete code:

<!DOCTYPE html>
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<style>
  body {
      font-family: 'Roboto', sans-serif;
      font-size: 24px;
  }
</style>
</head>
<body>

<h3>JavaScript Pop-up Window</h3>

<A href="http://www.bluegalaxy.info/webshopsolution/ssi.htm" target="_blank"
onClick="Popup('http://www.bluegalaxy.info/webshopsolution/ssi.htm','750','400'); return false;">Pop-up Demo Link</A>

<SCRIPT LANGUAGE="JavaScript">
  function Popup(page, windowWidth, windowHeight)
  {
  	OpenWin = window.open(page, "infoWindow",
        "toolbar=0, location=0, directories=0, status=1, menubar=0, scrollbars=1, resizable=1, width=" +
        windowWidth + ",height=" + windowHeight + ",top=100, left=200");
  }
</SCRIPT>

</body>
</html>

One more thing to note about this example is the pop-up window itself uses a little bit of JavaScript to provide a “Close Window” link. For example:

This link uses the built-in JavaScript top.close() method. For example:

<a href="javascript:top.close()">Close<BR>Window</a>

For more information about the JavaScript examples shown on this page see:
alert()
popup boxes
window.open()
close()

Leave a Reply