JavaScript overlay using Prototype and Script.aculo.us
Tuesday, May 27th, 2008As part of the interface for a web application, I wrote the following code to implement a modal dialogue box in JavaScript (similar to the Lightbox effect).
While there are a few different examples of this effect that I could have used, I was after something straight-forward and lightweight with clear separation of design (CSS) and presentation logic (JavaScript).
function DialogOverlay(content, container) { // Manage arguments and assign defaults, if (typeof container == 'undefined' ) container = document.body; if (null == (this.container = $(container))) throw("container is not valid"); // Assign instance variables this.content = content; this.overlay = new Element('div', { 'class': 'overlay' }).hide(); this.dialog = new Element('div', { 'class': 'dialog' }).hide(); // Hide the overlay when clicked. Ignore clicks on the dialog. Event.observe(this.overlay, 'click', this.hide.bindAsEventListener(this)); Event.observe(this.dialog, 'click', function(event) { Event.stop(event) }); // Insert the elements into the DOM this.dialog.insert(this.content); this.container.insert(this.overlay); this.container.insert(this.dialog); // Content may have been hidden if it is embedded in the page content.show(); this.dialog.hide(); } DialogOverlay.prototype.show = function() { new Effect.Appear(this.overlay, { duration: 0.5, to: 0.8 }); this.dialog.show(); return this; }; DialogOverlay.prototype.hide = function(event) { this.dialog.hide(); this.overlay.hide(); return this; };
Adding a dialogue object to your page is simple:
<script type="text/javascript"> var dialog = new Element('div'); dialog.insert(new Element('h2').insert('Dialogue')); var overlay = new DialogOverlay(dialog); </script>
In addition, you'll need some CSS to control the presentation of the overlay and dialogue box:
.overlay { width: 100%; height: 100%; background: black; position: fixed; top: 0; left: 0; z-index: 98; } .dialog { width: 50%; min-height: 50%; background: white; position: fixed; top: 25%; left: 25%; z-index: 99; }
I uploaded the JavaScript class (overlay.js) and made a quick example page to show it working.