Binding GreaseMonkey onclick

When I write a GreaseMonkey script, if I create a div and set onclick to warn that it works:

var btn = document.createElement('div'); btn.setAttribute('onclick',"alert('clicked!');");

However, if I ask you to do something else as previously defined, this will not work:

function graphIt() {...}; var btn = document.createElement('div'); btn.setAttribute('onclick',"graphIt();");

Is it possible to associate a function with an onclick event for a div?

+7
greasemonkey
source share
1 answer

Your problem is that since you set an attribute for a row, it evaluates the row in the context of the page itself, which does not have a graphIt function.

You must call the addEventListener method, for example:

 function graphIt() {...}; var btn = document.createElement('div'); btn.addEventListener("click", graphIt, false); 
+10
source share

All Articles