Making a Popup Window with HTML and JavaScript
by Castwide on 1-2-2008 Tags: code, drag-and-drop, javascript, popup 0 commentsThe DND library is a powerful JavaScript component that makes it easy to add drag-and-drop capabilities to web page elements. In this article we'll use DND to simulate a popup window.
The DND library also requires the Prototype and CFX libraries, so we'll need to add the following code to the page's head element:
<script language="javascript" type="text/javascript" src="prototype.js"></script>
<script language="javascript" type="text/javascript" src="cfx.js"></script>
<script language="javascript" type="text/javascript" src="dnd.js"></script>
Here's the HTML code for the window:
<div id="popup">
<div id="popup-bar">
<a href="#" id="popup-close">Close</a>
</div>
<p>
This is a movable popup window.
</p>
</div>
The #popup-bar div will behave like a title bar, letting users move the window by dragging and dropping it around the screen.
Next we'll add some style to the window:
#popup {
width: 320px;
height: 240px;
border: 1px solid #000000;
}
#popup-bar {
height: 20px;
background-color: #0000FF;
text-align: right;
}
#popup-bar a {
color: #FFFFFF;
}
With the window's HTML and CSS in place, we only need one line of JavaScript code to make it movable:
DND.enable('popup-bar', 'popup');
The DND.enable() function requires at least two arguments: the element to be used as a button and the element to be moved when the button is dragged. The button and the moved element can be the same. This example uses the title bar as the button.
For users' convenience, we'll also add the ability to close the window:
Event.observe('popup-close', 'click', function(e) {
$('popup').hide();
});
And that's all there is to it! This code should be easy to integrate into rich web applications and Web 2.0 technologies.