See that red beetle in the upper-right hand corner? I create that after the page loads, using Prototype. In fact, all the auxillary content in the header is created after the page loads. It’s not site content and it’s not navigation; it’s just for fun, so why load it before the “real” content, right?!
Ok, first, to add content using Prototype, I recommend that you already know or have the content you want to add to the DOM. For example, I wanted to add that red beetle to the DOM using Prototype. I already had the HTML coded up and here’s what it looked like…
<a href="#" onclick="beetles(); return false;">
<img src="/images/beetle1.png" alt="" id="beetle1" border="0" />
</a>
It’s a lot easier if you know and have the HTML code you’re trying to duplicate in Prototype. So, to add this content to the DOM after the page has loaded, we use the following Prototype functions: Element constructor, Element.insert, Element.update and document.observe. And here’s what the Prototype code looks like…
document.observe('dom:loaded', function() {
var linkBeetle1 = new Element('a', {
href: '#',
onclick: 'beetles(); return false;'
});
var beetle1 = new Element('img', {
src: '/images/beetle1.png',
id: 'beetle1',
alt: '',
border: '0',
});
linkBeetle1.update(beetle1);
$('header').insert(linkBeetle1);
};
new Element – creates a new HTML element with the provided attributes.
.update – updates/replaces the content of the element with the provided content. In this case, we’re attaching the <img> to the <a href> tag.
.insert – attaches the newly created element into the document to the element you specify.
document.observe(‘dom:loaded’… – this will make it so that the content is loaded after the page has been loaded (but before the images are loaded).
And that’s all there is to it!