onclick added with Tampermonkey is not calling the function?

Archival picture Archival · May 23, 2013 · Viewed 9.6k times · Source

If I create a div programmatically with Tampermonkey:

HTML:

<div onclick="myfunc()"/>

script:

function myfunc() { alert("clicked"); }

then click on the div; myfunc is not called in my script.

How can I get this to work?

(I use TM/jQuery to add the div to a page and I would like to attach some functionality to it. I assume I have to redirect the function call in the HTML to the proper place. I also use GM_ functions so I can't just insert the code directly.)

Answer

Brock Adams picture Brock Adams · May 23, 2013

The problem is that since you're setting the attribute to a string, it's evaluating the string in the target-page scope, which doesn't have a myfunc function. myfunc resides in the userscript scope.

As a general rule, you should never use onclick anyway, but this goes triple for userscripts.

Make the element easily selectable, like:

<div id="gmMyDiv"></div>


Then, either use the addEventListener() method, like this:

function myfunc (zEvent) {
    alert ("clicked"); 
}

var myDiv   = document.querySelector ("#gmMyDiv");
if (myDiv) {
    myDiv.addEventListener ("click", myfunc , false);
}


Or since you are using jQuery:

function myfunc (zEvent) {
    alert ("clicked"); 
}

$("#gmMyDiv").click (myfunc);