Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick added with Tampermonkey is not calling the function?

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

like image 594
Archival Avatar asked May 23 '13 01:05

Archival


People also ask

How does Onclick implement function?

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.

Can you add onclick to CSS?

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.

Can we use Onclick in button tag?

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.

Does Onclick only work once?

addEventListener can add multiple events to a particular element. onclick can add only a single event to an element.


1 Answers

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);
like image 194
Brock Adams Avatar answered Oct 30 '22 13:10

Brock Adams