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.)
To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
To use CSS onClick, you'll essentially need to create a pseudo class. You'll use CSS selectors and the checkbox hack to produce something like an OnClick function. And you can get away with this if you just want to use only CSS to make some minor changes, like border width or border radius.
The Html <button onclick=" "> is an event attribute, which executes a script when the button is clicked. This attribute is supported by all browsers. It is also used to call a function when the button is clicked.
addEventListener can add multiple events to a particular element. onclick can add only a single event to an element.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With