Javascript Pop Up

There are many scripts out there that provide customized pop ups for your pages. Rather than trying to supply a one size fits all script this page demonstrates how you can easily write your own popups, giving you complete control over what you show your users without costing you a cent.

The method

Adding your own popups is amazingly simple. The technique I demonstrate here uses the innerHTML property of a div element to create the DOM objects for the popup. The objects created are then added to the document.body using the DOM method 'appendChild'.

It is possible to write directly to the document.body innerHTML property, however this can often cause wierd rendering issues and it has proved safer to use the method shown here.

Below you'll find an example of this method in it's simplest form. A div element is created and it's innerHTML set to 'Hello World'. The firstChild of the element (which will be a #text element) is then appended to the body of the web page.

<html xmlns="" xml:lang="en"> <head> <script type="text/javascript"> window.onload = function() { var div = document.createElement('div'); div.innerHTML = 'Hello World'; document.body.appendChild(div.firstChild); }; </script> </head> <body> </body> </html>

An example

Once you grasp this method it is a very short step to adding in your own popups. For this example I've defined the following css rules.

.popUp { position: absolute; top: 1000px; left: 200px; text-align: center; padding: 5px; border: 1px solid black; background: white; }

These rules define how my popup will look. I'm positioning it absolutely so it won't interfere with other elements on the page. I've set it to show 1000px from the top and 200px from the left of the page. I then center align all the cell contents, add some padding, a border and a background color.

I then define my createPopUp function as follows..

function createPopUp(popUpCode) { var div = document.createElement('div'); div.innerHTML = popUpCode; document.body.appendChild(div.firstChild); }

So now all that's required is to supply the createPopUp function with some HTML code and it will be added to the page. To prove how flexible this method really is I've put some HTML code into the textarea below. Feel free to edit the code provided to anything you want and then test the result with the 'Create PopUp' button.

The code calling the createPopUp function is very simple.

<button onclick='createPopUp(document.getElementById("popUpCode").value)'>Create PopUp</button>

Things to note

The createPopUp function I've created does nothing to add functionality to the popup, which is why the example popup code above includes it's own close button. It would be quite easy to modify the script to put a common shell around your popups, adding a close button or even drag and drop functionality.


If you've got any questions or feedback about this article please post them in the Dynamic Tools Javascript Forum.