...

View Full Version : DOM buttons and onclick events



cfan
07-27-2006, 11:38 PM
Hello,

I'm trying to do something fairly straightforward: write a GreaseMonkey script that uses DOM to add a button to a page. Here's my code:


var elmReportButton = document.createElement('button');
elmReportButton.appendChild(document.createTextNode("Report"));
elmReportButton.onclick = function(){ alert("Hi!"); }
elmThreadURLButton.appendChild(elmReportButton);

Eventually I want to replace alert("Hi!"); with something more interesting, but let's use that as an example for now.

Unfortunately, this doesn't work. The JavaScript console just says "Component not defined" on the onclick line. (I've tried this with both function references and anonymous function declarations, and get the same result each time). What am I doing wrong?

Thanks!

_Aerospace_Eng_
07-27-2006, 11:46 PM
Try creating an input type="button" instead

var elmReportButton = document.createElement('input');
elmReportButton.setAttribute('type','button');
elmReportButton.setAttribute('value','Report');
elmReportButton.onclick = function(){ alert("Hi!"); }
elmThreadURLButton.appendChild(elmReportButton);

cfan
07-27-2006, 11:48 PM
Nope. Still get the same error.

Kravvitz
07-28-2006, 03:19 AM
Try adding the event to the element after you've added it to the page's DOM.

cfan
07-28-2006, 06:35 PM
Thanks for the suggestion, but that didn't work either. :(

Does it matter that this is a GreaseMonkey script, and that the DOM elements are being added to the page after it's already been created?

Does it matter that I'm not using a <form> element?

I'm racking my brains on this one but just can't seem to understand why the script won't execute.

vwphillips
07-28-2006, 07:21 PM
dont know about GreaseMonkey script
but as expected this works



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script language="JavaScript" type="text/javascript">
/*<![CDATA[*/
function Add(){
var elmReportButton = document.createElement('input');
elmReportButton.setAttribute('type','button');
elmReportButton.setAttribute('value','Report');
elmReportButton.onclick = function(){ alert("Hi!"); }
document.getElementById('fred').appendChild(elmReportButton);
}
/*]]>*/
</script></head>

<body onload="Add();">
<div id="fred"></div>
</body>

</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum