In an attempt to create a custom emote script for a website, an issue arose resulting in the error "Uncaught ReferenceError: function is not defined with onclick."
The script contained span tags with onclick attributes that called functions. However, when these buttons were clicked, the functions were not being recognized.
The solution lies in avoiding the use of onclick attributes from userscripts, as they operate in a sandboxed environment separate from the target-page scope. Instead, event listeners should be used.
To implement event listeners, follow these steps:
Instead of using onclick attributes, replace them with addEventListener():
<span>
document.getElementById("mySpan").addEventListener("click", myFunction, false);
As we cannot directly pass data to event listeners, we can use data attributes:
<span>
targetSpans = emoteTab[2].querySelectorAll("span[data-usage]"); for (var J in targetSpans) { targetSpans[J].addEventListener("click", appendEmote, false); }
function appendEmote(zEvent) { var emoteUsage = this.getAttribute("data-usage"); shoutdata.value += emoteUsage; }
1. Unique IDs:
Ensure that each ID is used only once per page. Using duplicate IDs is invalid.
2. Event Handler Removal:
Using .outerHTML or .innerHTML will remove existing event handlers. Be cautious when using these methods.
The above is the detailed content of Why is my `onclick` function undefined in a userscript, and how can I fix it using event listeners?. For more information, please follow other related articles on the PHP Chinese website!