10

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.)

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Archival
  • 638
  • 2
  • 6
  • 13

2 Answers2

19

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);
Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
1

assign a field to the function in the "window" object

// ==UserScript==
// @name        Content Script Example, grant none
// @grant       none
// ==/UserScript==

function helper() {
    alert('helper');
}

window.helper2 = helper;

element.innerHTML = "<button onclick='window.helper2()'>Click Me</button>" ;

Credits: https://wiki.greasespot.net/Content_Script_Injection

Sridhar Sarnobat
  • 25,183
  • 12
  • 93
  • 106