views:

229

answers:

2

Guys,

So I'm coding a Greasemonkey script for this website.. Anyway, my problem is I can't attach the onclick event into my newly created anchor.

I don't know what's wrong, maybe because I'm in Greasemonkey thats why It didn't work as expected?

function createButton() {
    var a = document.createElement('a');
    var css = document.createElement('style');
    css.type = 'text/css';
    css.innerHTML = '#prt { position:absolute; right:3em; top: 6em; font-family: Arial,Helvetica,sans-serif; font-weight:bold; font-size:125%; background: #777777 none repeat scroll 0 0; color: white; padding: 6px 12px;}'
    a.href = '#';
    a.innerHTML = 'Print Topic';
    a.id = 'prt';
    a.onclick = getTopic; // DOESN'T WORK
    document.body.insertBefore(a, document.body.lastChild);
    document.body.appendChild(css);
}

I tried the other technique like setAttribute

a.setAttribute('onclick', function() { alert("hey"); });

setAttribute also didn't work..

How come??

Hey guys,

I made it work. Someone helped me over the IRC #greasemonkey.. Thanks broquaint!!

So the problem of using setAttribute or the .onclick property of the element is greasemonkey doesn't support them instead it will return "Component not available" error in the JavaScript console.

If you experienced this problem before you must use

element.addEventListener ('click', myClickHandler, false);

Here's the Wiki: http://wiki.greasespot.net/XPCNativeWrapper#Event_Handlers

+2  A: 

Use the attachEvent method of the anchor -

a.attachEvent(getTopic)

Edit - attachEvent is IE only. For Firefox, you'll have to use addEventListener -

a.addEventListener(getTopic)

Jez
+1  A: 

Try wrapping it in an anonymous function

a.onclick = function(){
    getTopic();
}
Fire Crow
Thanks.. But the button didn't show up after wrapping that function.
rymn