Javascript: onclick/onsubmit for dynamically created button

Christian picture Christian · Aug 15, 2011 · Viewed 87.2k times · Source

I dynamically create a button in the way I found in the Internet:

 Page = function(...) {
   ...
 };

 Page.prototype = {
   ...
   addButton : function() {
     var b = content.document.createElement('button');
     b.onclick = function() { alert('OnClick'); }
   },
   ...
 };

Unfortunately, it's not working and throwing the following error:

  Error: [Exception... "Component is not available"  nsresult: "0x80040111
  (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: chrome://knowledgizer/content
  /knowledgizer.js :: <TOP_LEVEL> :: line 137"  data: no]
  Source File: chrome://browser/content/tabbrowser.xml Line: 434

The solution with setAttribute work:

b.setAttribute("onClick", "alert('OnClick')");

However, I want to call a class method (instead of alert), and the b.onclick syntax looks better in that respect, I hope/think. is this onclick case senstive? Because if I write

b.onClick = function() {alert("OnClick");} // notice the spelling onclick vs onClick

I don't get the error above, but it's still not working, i.e. I don't get the alert. I'm thankful for any tips.

As a bonus question: How can I avoid that the current page is reload when the button is clicked? I just like call a method and not to cause a page reload.

Thanks and best regards,

Christian

Answer

Walialu picture Walialu · Aug 15, 2011
var foo = function(){
  var button = document.createElement('button');
  button.innerHTML = 'click me';
  button.onclick = function(){
    alert('here be dragons');return false;
  };
  // where do we want to have the button to appear?
  // you can append it to another element just by doing something like
  // document.getElementById('foobutton').appendChild(button);
  document.body.appendChild(button);
};