I need to display html elements as contents of a popup panel using javascript in my firefox addon.
Displaying popup using SDK is what I'm looking for but I don't want to use SDK.
panel:
<popupset id="mainPopupSet">
<panel id="htmlPanel" type="arrow">
i want to use html elements like p,div,span, etc here.
</panel>
</popupset>
javascript to open panel:
document.getElementById('htmlPanel').innerHTML = 'my custom contents';
document.getElementById('htmlPanel').openPopup(null, "before_start", 0, 0, false, false);
it seems some elements are allowed but with different behavior! i also need to set CSS for elements inside panel.
I figure it out how to do it using an iframe
changed the XUL as follow:
<popupset id="mainPopupSet">
<panel id="htmlPanel" type="arrow">
<html:iframe id="htmlContainer"/>
</panel>
</popupset>
and create a javascript function to set html contents:
function setupPanel(contents, width, height)
{
var iframe = document.getElementById("htmlContainer");
iframe.setAttribute("src","data:text/html;charset=utf-8," + escape(contents));
iframe.width = width || 300; //default width=300
iframe.height = height || 300; //default height=300
}
and usage:
setupPanel("<p>this is raw HTML.</p>");
document.getElementById('htmlPanel').openPopup(null, "before_start", 0, 0, false, false);
thanks for your hints.
With animation can copy paste to scratchpad to run it.
var win = Services.wm.getMostRecentWindow('navigator:browser');
var panel = win.document.createElement('panel');
var props = {
type: 'arrow',
style: 'width:300px;height:100px;'
}
for (var p in props) {
panel.setAttribute(p, props[p]);
}
win.document.querySelector('#mainPopupSet').appendChild(panel);
panel.addEventListener('popuphiding', function (e) {
e.preventDefault();
e.stopPropagation();
//panel.removeEventListener('popuphiding', arguments.callee, false); //if dont have this then cant do hidepopup after animation as hiding will be prevented
panel.addEventListener('transitionend', function () {
//panel.hidePopup(); //just hide it, if want this then comment out line 19 also uncomment line 16
panel.parentNode.removeChild(panel); //remove it from dom //if want this then comment out line 18
}, false);
panel.ownerDocument.getAnonymousNodes(panel)[0].setAttribute('style', 'transform:translate(0,-50px);opacity:0.9;transition: transform 0.2s ease-in, opacity 0.15s ease-in');
}, false);
panel.openPopup(null, 'overlap', 100, 100);
to display html in it, do createElementNS('html namespace i cant recall right now','iframe') then set the src of this to the html you want it to display
the type:'arrow' here is important
Since this appears to be an overlay of browser.xul, if your panel will display static content or a simple template, you can take advantage of the fact that the XHTML namespace is already declared.
<popupset id="mainPopupSet">
<panel id="htmlPanel" type="arrow">
<html:div id="htmlplaceholder">
<html:p>Lorem ipsum</html:p>
<html:p>foo <html:strong>bar</html:strong></html:p>
</html:div>
</panel>
</popupset>
The Add-on SDK hosts the html content inside an iframe, perhaps you should consider this for more complex cases.
Related
i have a link in my main page that uses ajax to retrieve a PDF which is displayed in an Iframe, i am trying to detect scroll event of the PDF document and display a message or do something. i have tried different solutions from other solutions on stackoverflow and google search in general and couldn't find a good solution.
Main.php
<html>
<!--ajax request-->
<script type="text/javascript">
$(document).on('click','#nextpdf',function(event) {
event.preventDefault();
var reg = $(this).attr("href");
var str = reg.split('?')[1];
$.ajax({
type: "GET",
url: '../functions/pdfreader.php',
data: 'pdfxs='+str+'',
cache:false,
async: false,
success: function(data) {
// data is ur summary
$('.refresh').html(data);
return false;
}
});//end of ajax
});
</script>
<?php
while($obj = $c_content->fetch())
{
$title = $obj['lecture_title'];
echo '<article class="comment2">
//pdf link
<div class="comment2-body">
<div class="text" style="color:#999;padding-right:130px;">
<p><a href="../functions/pdfreader.php?'.$title.'""
style="color:#999" id="nextpdf">'.$title.'</a></p>
</div>
</div>
</article>
';
}
?>
</html>
pdfreader.php
//detect iframe pdf scroll
<script type="text/javascript">
$("myiframe").load(function () {
var iframe = $("myiframe").contents();
$(iframe).scroll(function () {
alert('scrolling...');
});
});
</script>
<?php
........
while($obj = $gettrend->fetch())
{
$coursefile = $obj['lecture_content'];
//this is my iframe
echo '<div class="mov_pdf_frame"><iframe id="myiframe"
src="https://localhost/einstower/e-learn/courses/pdf/'.$coursefile.'"
id="pdf_content"
width="700px" height="800px" type="application/pdf">
</iframe></div>';
}
?>
The major problem here is that nothing happens when i scroll the pdf document, how can i detect scrolling?
i found this fiddle that works but i cant view the javascript solution. http://fiddle.jshell.net/czw8pbvj/1/
First off, $("myiframe") isn't finding anything, so it attaches a load event to nothing. 1) change it to $("#myiframe") or $("iframe").
Here's a working fiddle (for iframe scroll detection)
UPDATE: to detect the scroll within PDF document, you can't use iframe. For that, you need embed or object tags AND a JS-enabled PDF document (hopefully its your PDFs..), who can send messages to your page's JS (see this answer).
Unfortunately, I couldn't find a scroll event in Adobe's Acrobat API Reference. It lists only these events:
Event type: Event names
App: Init
Batch: Exec
Bookmark: Mouse Up
Console: Exec
Doc: DidPrint, DidSave, Open, WillClose, WillPrint, WillSave
External: Exec
Field: Blur, Calculate, Focus, Format, Keystroke, Mouse Down, Mouse Enter, Mouse Exit, Mouse Up, Validate
Link: Mouse Up
Menu: Exec
Page: Open, Close
Screen: InView, OutView, Open, Close, Focus, Blur, Mouse Up, Mouse Down, Mouse Enter, Mouse Exit
So, basically, I think what you want just isn't possible as for now, at least with default rendering. With custom rendering (https://github.com/mozilla/pdf.js) it could be possible, though I'm not sure.
Apparently, it could be done with page scroll (see this issue). So back to iframes solution. :^D
Because this question is asked a long time ago, i think i need to help with my experience before.
The answer is: You can not
Why? because PDF is rendered by external apps, such as adobe pdf reader, foxit or else. And you can not attach event on them.
if you are using adobe reader, The only you can do is goto page, change zoom etc. Full example you can read here: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=8 (see. i bring you to page 8 directly instead to first page).
But, hei.. how if our client using another apps? we will confused more
The way to do this is only build your own pdf viewer.
we can using js library, like: http://www.bestjquery.com/2012/09/best-jquery-pdf-viewer-plugin-examples/
but here i only will show you to use pdf.js which created by mozilla.
main.php
<style>
.preview{
display:none;
width: 400px;
height: 400px;
border: 1px solid black;
}
</style>
file/test.pdf<br>
file/test1.pdf<br>
<div class="preview">
<iframe id="myiframe" frameborder="0" width="400px" height="400px" >not support iframe</iframe>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click', '#nextpdf', function(e){
e.preventDefault();
$('#myiframe').attr('src', $(this).attr('href'));
$('.preview').show();
});
//handle iframe on scroll
$('#myiframe').on('load', function () {
$(this).contents().scroll(function () {
console.log('scrolled');
}).click(function(){
console.log('clicked');
});
});
});
</script>
pdfreader.php
<?php
$path = 'file/';
$pdf = isset($_GET['pdfxs']) ? $path . $_GET['pdfxs'] : '';
if(!file_exists($pdf) || !mime_content_type($pdf) =='application/pdf') die('file not found');
?>
<div id="pdf-container">
<div id="pdf-box"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<script>
$(function(){
//original script : https://gist.github.com/fcingolani/3300351
function renderPDF(url, canvasContainer, options) {
var options = options || { scale: 1 };
function renderPage(page) {
var viewport = page.getViewport(options.scale);
var canvas = $(document.createElement('canvas'));
var renderContext = {
canvasContext: canvas[0].getContext('2d'),
viewport: viewport
};
canvas.attr('width', viewport.width).attr('height', viewport.height);
canvasContainer.append(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(renderPages);
}
renderPDF('<?=$pdf;?>', $('#pdf-box'));
});
</script>
Note: i put pdf on folder file/
in main.php you will notice that you can attach event scroll (and click too) to the pdf. because our pdf is not rendered by external apps now.
and the last part is, if you read pdfreader.php carefully, you will notice that you no need iframe anymore. You just need div, and then you can fully handle all event that do you want to your pdf : like scroll, click, change page, zoom, etc. why?? because your pdf is redered as canvas now (pdf.js render your pdf as HTML5 canvas). see full example of pdf.js
Please try this
iframe.on( "scroll", handler )
$("#frame").scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height())
alert('Bottom reached');
});
I found this in the JSFiddle that was referenced in the Fiddle you linked. The HTML field is empty. This CSS was in there, too.
body {
height: 1500px;
}
In the fiddle that you linked, the <iframe> has an ID of frame. I figured you can use the jQuery selector like $("#frame").
I think this will help you.
$("#myiframe").load(function () {
$(this).contents().scroll(function () {
//your code here
});
});
I try to implement a way to prevent the updating of values with mouse (actually when the three.js animation has started, launched with a click on button).
For the moment, I have the following dat.GUI menu:
Once "start" button is clicked, I would like to prevent user from modifying with mouse the parameters "Rotation x" and "Rotation y".
Here is the concerned part of code for this menu:
// Create GUI
var gui = new dat.GUI({
autoplace: false,
width: 350,
height: 9 * 32 - 1
});
var params = {
GreatCircle : '',
Rotationx : torusRotationInitX,
Rotationy : torusRotationInitY,
StartingVector : '',
ComponentVectorTheta : 15.0,
ComponentVectorPhi : 15.0,
CovariantDerivativeVector : '',
ComponentCovariantDerivativeTheta : 15.0,
ComponentCovariantDerivativePhi : 15.0
};
// Set parameters for GUI
gui.add(params, 'GreatCircle').name('Great Circle ');
controllerRotationx = gui.add(params, 'Rotationx', 0, 2*Math.PI, 0.001).name('Rotation x ');
controllerRotationy = gui.add(params, 'Rotationy', 0, 2*Math.PI, 0.001).name('Rotation y ');
...
When I click on reset button, I call the following function:
// Reset Button
resetButton.onclick = function ResetParameters() {
...
// Reinitialize parameters into gui
params.Rotationx = torusRotationInitX;
params.Rotationy = torusRotationInitY;
for (var i in gui.__controllers) {
gui.__controllers[i].updateDisplay();
}
render();
}
I don't know if there is an option for controller to lock these sliders which usually change their values. Is it possible?
Update 1
Maybe I could wrapper the dat.GUI menu into a div and make this div not clickable, is it a solution?
Update 2
I tried to apply the method used on Method for disabling a button in dat.gui?
Following this solution, I have added the extension into dat.gui, just after:
dat.controllers.FunctionController = (function (Controller, dom, common) {
...
});
The following added code snippet is:
function blockEvent(event)
{
event.stopPropagation();
}
Object.defineProperty(dat.controllers.FunctionController.prototype, "disabled", {
get: function()
{
return this.domElement.hasAttribute("disabled");
},
set: function(value)
{
if (value)
{
this.domElement.setAttribute("disabled", "disabled");
this.domElement.addEventListener("click", blockEvent, true);
}
else
{
this.domElement.removeAttribute("disabled");
this.domElement.removeEventListener("click", blockEvent, true);
}
},
enumerable: true
});
Is extension code well located into dat.GUI source?
Then, I set the property "disabled" into my code to prevent user from sliding "controllerRotationx" with mouse (once start button is pressed):
if (animation)
controllerRotationx.__li.disabled = true;
Unfortunately, my method doesn't work : when animation is started, I can still move the slider contained into "controllerRotationx".
I saw that above link (Method for disabling a button in dat.gui?), this was about a button and not for a slider, does it change anything for my case?
I didn't find an explicit controller for the slider.
I would do this. The slider is not a form element, there's nothing to disable in the traditional w3c sense. Luckily we can use pointer-events and disable it properly as if it were a form element using just public dat.gui properties.
var speeder = menu.add(text, 'speed', -5, 5);
speeder.domElement.style.pointerEvents = "none"
speeder.domElement.style.opacity = .5;
The solution given by #Radio works pretty well. But, with sliders, the slider is a sibling of the text box's DOM element. We need to disable pointer events on the div which contains all the controls (and which is not exposed directly by dat.gui). So,
var speeder = menu.add(text, 'speed', -5, 5);
// disables the text box
speeder.domElement.style.pointerEvents = "none"
// disables all controller elements related to "speeder"
speeder.domElement.parentElement.style.pointerEvents = 'none'
When the Start button is pressed, set:
controllerRotationx.__li.setAttribute( "style", "display: none" );
thanks for tips
on my side i hack the Common controller
so able to chainning.
gui.add(this, '_screenW').disable(true);
Common.extend(controller, {
disable: function disable(v) {
this.domElement.style.pointerEvents = v?"none":"auto";
this.domElement.style.opacity = v?.5:1;
return controller;
},
I'm programming a firefox addon and using a panel to display info on a video, everything works fine althought I can't make the panel transparent. I define the panel styling in the html file as follow:
<html>
<head>
<meta charset="utf-8" />
<style type="text/css" media="all">
html
{
opacity:0.1;
border-style:none;
resize:none;
}
textarea
{
background-color:transparent;
resize: none;
border-style:none;
}
</style>
</head>
<body>
<textarea id="text" readonly=true rows="3" cols="60"></textarea>
</panel>
</body>
</html>
Except the panel is not transparent only the text area is. I tried with:
opacity:1 for textarea
It doesn't work either way. What am I doing wrong? Is this even possible?
From what I understand :
html
{
opacity:0.1;
border-style:none;
resize:none;
}
only applies to the panel content not to the panel itself. I found a post on this subject but it is outdated since the sdk/panel.js mentionned in the post is not the same anymore.
Anyway I tried downloading the panel.js and replacing the current one, but it doesn't seem to affect the panel I display at all. The panel is still white and the border-radius option does not work either. (I should say that I replaced all the "./" with "sdk/" as mentionned in that post).
Ok here is a pure addon sdk solution:
let myPanel = Panel({
width: 180,
height: 180,
contentURL: 'data:text/html,<textarea style="width:120px; height:80px;">this is my textarea</textarea>'
})
let { getActiveView }=require("sdk/view/core");
getActiveView(myPanel).setAttribute("noautohide", true);
getActiveView(myPanel).setAttribute("level", 'top');
getActiveView(myPanel).setAttribute("style", 'background-color:rgba(0, 0, 0, 0.2);');
You can't style the panel provided in the SDK, only the content but you can definitely follow the procedure you mention and provide your modified panel.
I had to solve this same problem today (transparent panel in SDK). The trick is getting at the anonymous content:
function makePanelTransparent() {
// Get the panel element in the XUL DOM and make its background transparent.
const { getActiveView } = require('sdk/view/core');
const el = getActiveView(panel);
el.style.background = 'rgba(0,0,0,0)';
// Go up the XUL DOM till you hit the Document (nodeType 9).
let parentNode = el;
while (parentNode !== null && parentNode.nodeType !== 9) {
parentNode = parentNode.parentNode;
}
if (!parentNode) {
console.error('unable to find the document parent; giving up');
return;
}
// Now that we've found it, call the document a document.
const xulDocument = parentNode;
// Use the document pointer to access and style 'anonymous' content.
const xulContainer = xulDocument.getAnonymousElementByAttribute(el, 'class', 'panel-arrowcontent')
xulContainer.style.background = 'rgba(0,0,0,0)';
xulContainer.style.boxShadow = 'none';
}
This works for me. Hope it helps some other person in the next 1-5 years ;-)
I found out that you could create a panel with transparency this way:
var win = Services.wm.getMostRecentWindow('navigator:browser');
var panel = win.document.createElement('panel');
var screen = Services.appShell.hiddenDOMWindow.screen;
var props = {
noautohide: true,
noautofocus: false,
level: 'top',
style: 'padding:15px; margin:0; width:' + screen.width + 'px; height:' + screen.height + 'px; background-color:rgba(180,180,180,.5);'
}
for (var p in props) {
panel.setAttribute(p, props[p]);
}
win.document.querySelector('#mainPopupSet').appendChild(panel);
panel.addEventListener('dblclick', function () {
panel.parentNode.removeChild(panel)
}, false);
panel.openPopup(null, 'overlap', screen.availLeft, screen.availTop);
To embed an iframe remember to set the path to your ".html" as:
"resource://"id of your addon"-at-jetpack/data/custom_panel.html".
Here is my code :
var win = Services.wm.getMostRecentWindow('navigator:browser');
var panel = win.document.createElement('panel');
var screen = Services.appShell.hiddenDOMWindow.screen;
var props = {
noautohide: true,
noautofocus: false,
backdrag: true,
level: 'top',
style: 'padding:10px; margin:0; width:530px; height:90px; background-color:rgba(180,180,180,.5);'
}
for (var p in props) {
panel.setAttribute(p, props[p]);
}
var iframe = win.document.createElement('iframe');
iframe.setAttribute('src','resource://"id of your addon"-at-jetpack/data/custom_panel.html');
panel.appendChild(iframe);
win.document.querySelector('#mainPopupSet').appendChild(panel);
panel.addEventListener('dblclick', function () {
panel.parentNode.removeChild(panel)
}, false);
panel.openPopup(null, 'overlap', screen.availLeft+screen.width/2-256, screen.availTop+760);
Thanks Noitidart for the help.
I have a problem when apply an Ext.ComboBox over an existing html select item, even if the existing content makes the html select about 20px (by it's content non static width is set), the Ext.ComboBox will resize to a sort of default, large, width value.
There's a way to auto resize the Ext.ComboBox based on the existing items and no using the default width?
Even if I know which best tool Ext is, this issue will let my colleagues to discard Extjs.
Thanks in advance
You can't technically make a combo "auto width" -- Ext actually converts the <select> into a regular <input> behind the scenes, and <input> elements have to have a width/size specified. However, you can trick Ext into sizing the combo based on the existing <select> which should give you the same end result. Here's an example from the Ext combo demo page, where I have modified the width config value:
var converted = new Ext.form.ComboBox({
typeAhead: true,
triggerAction: 'all',
transform:'state',
width: Ext.fly('state').getWidth(),
forceSelection:true
});
The obvious caveat would be that if you subsequently modify the list after it's rendered, the combo will not resize itself automatically and you'd have to figure out a way to resize it yourself.
Use this code:
Ext.ux.ResizableComboBox = Ext.extend(Ext.form.ComboBox, {
initComponent: function(){
Ext.ux.ResizableComboBox.superclass.initComponent.call(this);
this.on('render', this.resizeToFitContent, this);
},
resizeToFitContent: function(){
if (!this.elMetrics){
this.elMetrics = Ext.util.TextMetrics.createInstance(this.getEl());
}
var m = this.elMetrics, width = 0, el = this.el, s = this.getSize();
this.store.each(function (r) {
var text = r.get(this.displayField);
width = Math.max(width, m.getWidth(text));
}, this);
if (el) {
width += el.getBorderWidth('lr');
width += el.getPadding('lr');
}
if (this.trigger) {
width += this.trigger.getWidth();
}
s.width = width;
this.setSize(s);
this.store.on({
'datachange': this.resizeToFitContent,
'add': this.resizeToFitContent,
'remove': this.resizeToFitContent,
'load': this.resizeToFitContent,
'update': this.resizeToFitContent,
buffer: 10,
scope: this
});
}
});Ext.reg('resizable-combo', Ext.ux.ResizableComboBox);
In addition to what bmoeskau suggests, you can use an xtemplate for your combo's items. This will give you the ability to change the look of the item. You can wrap text, add images, etc.
add a listener to the afterrender event and set the width if the list (the div that drops down ) to auto e.g.
afterrender: function(combo){
combo.list.setSize('auto', 0);
combo.innerList.setSize('auto', 0);
}
The reason I am using afterrender and not render is because if you set lazyInit to false it will set the list width, so in afterrender you override that setWidth
I'm pretty sure you can get ExtJs to render whatever html items you need to, in the way you want them to be rendered.
here's some code from the Examples/Form/Combos.js file:
var converted = new Ext.form.ComboBox({
typeAhead: true,
triggerAction: 'all',
transform:'state',
width:20, //<-- set this config value!
forceSelection:true
});
in the code that you're using to transform the combo, just specify a width for the ExtJs combo.
I'm pretty new to Javascript and have been trying to achieve some fading effects on a website.
I've managed to hammer together the effects I want and everything's working fine on Firefox & Safari. However IE doesn't like it. The first script to change the background colour works but the second script to fade in the content does nothing.
I'm calling the scripts from the head as follows:
window.onload=siteIntro;
And the Javacript which is not working is here. Any help or suggestions would be appreciated, the live site can be viewed if needed.
Many Thanks
// ################# Fade Divs ###############################
function Fade(objID,CurrentAlpha,TargetAlpha,steps){
var obj = document.getElementById(objID);
CurrentAlpha = parseInt(CurrentAlpha);
if (isNaN(CurrentAlpha)){
CurrentAlpha = parseInt(obj.style.opacity*100);
if (isNaN(CurrentAlpha))CurrentAlpha=100;
}
var DeltaAlpha=parseInt((CurrentAlpha-TargetAlpha)/steps);
var NewAlpha = CurrentAlpha - DeltaAlpha;
if (NewAlpha == 100 && (navigator.userAgent.indexOf('Gecko') != -1 && navigator.userAgent.indexOf('Safari') == -1)) NewAlpha = 99.99;
obj.style.opacity = (NewAlpha / 100);
obj.style.MozOpacity = obj.style.opacity;
obj.style.KhtmlOpacity = obj.style.opacity;
obj.style.filter = 'alpha(opacity='+NewAlpha+')';
if (steps>1){
setTimeout('Fade("'+objID+'",'+NewAlpha+','+TargetAlpha+','+(steps-1)+')', 50);
}
}
// ################# Toggle content div visibility ###############################
function mainVis(showMain) {
document.getElementById(showMain).style.visibility ="visible";
}
function pageSwitch(show0, hide0, hide1, hide2, hide3) {
document.getElementById(show0).style.visibility ="visible";
document.getElementById(hide0).style.visibility ="hidden";
document.getElementById(hide1).style.visibility ="hidden";
document.getElementById(hide2).style.visibility ="hidden";
document.getElementById(hide3).style.visibility ="hidden";
}
function pg1() {
pageSwitch('prices', 'icon', 'about', 'map', 'news');
Fade('prices','0',100,30)
}
function pg2() {
pageSwitch('about', 'icon', 'prices', 'map', 'news');
Fade('about','0',100,30)
}
function pg3() {
pageSwitch('map', 'icon', 'about', 'prices', 'news');
Fade('map','0',100,30)
}
function pg4() {
pageSwitch('news', 'icon', 'map', 'about', 'prices');
Fade('news','0',100,30)
}
// ################# Site Intro Functions ###############################
function siteIntro() {
setTimeout("NLBfadeBg('b1','#FFFFFF','#000000','3000')",2000);
mainVis('main');
setTimeout("Fade('main','',100,30)",5000);
}
MS filters only apply to elements that "have layout".
To force layout, you can give the element a width or a height, or use the old zoom: 1; trick.
Not sure if this is the cause of your problems, but you could try it.
You can read more about hasLayout here.
Another thing, instead of:
setTimeout('Fade("'+objID+'",'+NewAlpha+','+TargetAlpha+','+(steps-1)+')', 50)`
you can simply write:
setTimeout(function() { Fade(objID, NewAlpha, TargetAlpha, steps-1); }, 50)`
Unless you are doing it just for fun and/or learning, just use an existing JS library instead of re-inventing the wheel.
Maybe you can take advantage of an out-of-the-box cross browser script like this
http://brainerror.net/scripts/javascript/blendtrans/
Or use jQuery (which is great with animating and effects) or any other JS library
This might not be an answer you are looking for, but you shouldn't be doing this: you can use jQuery to do this for you. One or two lines of code, and it is cross browser compatible.