Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
TagUrIt
Jan 24, 2007
Freaking Awesome
I'm trying to write a greasemonkey script that adds, among other things, a button to the page. I'm fairly certain the rest of my code works, but I simply cannot figure out how to add the onclick event for the new button. I'm writing this solely for FF3, so I'm not too concerned about stuff not working in IE or whatever.

code:
var button = document.createElement("button");
button.type  = "button";
button.value = "Submit data!";
button.name  = "submitButton";

//what googling suggests is right...but doesn't work
//button.onclick = new Function("alert('lol')");
//button.onclick = new Function (evt) {alert('hi');};

//ditto
//button.onclick = new Function("doStuff()");
//button.onclick = new Function (event) {doStuff();};


// This works! (I think)
//button.setAttribute("onclick", "alert('hi')");

// but this doesn't :(
//button.setAttribute("onclick", "doStuff()");

// And some other possibilities via google
//button.setAttribute("onclick", "doStuff()");
//button.addEventListener('onClick', 'doStuff()', false);
Appending the button to the page either before or after adding the handler doesn't seem to make any difference.

So, in general, if I'm dynamically creating a button and adding it to the page, how do I actually set the onclick event for it?

edit: I figured it out thanks to stuff on the previous page. I had the wrong type of event named (onclick or onClick instead of click).
code:
button.addEventListener('click', function (){doStuff();}, false);

TagUrIt fucked around with this message at 17:33 on Apr 25, 2009

Adbot
ADBOT LOVES YOU

TagUrIt
Jan 24, 2007
Freaking Awesome
Indeed it does. :)

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply