1

I had a previous question, and someone told me that document.write wipes all functions out, and to use insertAdjacentHTML instead, but when I tried it, it has the same result. The code still says that myFunction is not defined. What am I doing wrong?

// ==UserScript==
// @name         Replace Multiple Spaces With One Space
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.google.com/search?q=replaceSpace
// @grant        none
// ==/UserScript==

document.body.insertAdjacentHTML("beforeEnd", "<input type='text' id='myText' value='Some text...'>");
document.body.insertAdjacentHTML("beforeEnd", "<p id='demo'></p>");
document.body.insertAdjacentHTML("beforeEnd", "<button onclick='myFunction()'>Try it</button>");

function myFunction() {
  var string = document.getElementById("myText").value;
  string = string.replace(/\s\s+/g, ' ');
  document.getElementById("demo").innerHTML = string;
}
frosty
  • 2,559
  • 8
  • 37
  • 73
  • Is `myFunction()` defined in the global scope? Please provide minimum reproducible code. – TimTIM Wong Aug 03 '20 at 18:37
  • Sorry about the confusion in your previous question. `myFunction` is defined in your userscript, online listeners are not working, as they need a global function. Try this: Remove the online listener and in your userscript do: `document.getElementById('demo').nextElementSibling.addEventListener('click', myFunction);` Put the code line after inserting new content to the page. – Teemu Aug 03 '20 at 18:43
  • @TimTimWong This is all of the code. It's being run in tampemonkey. – frosty Aug 03 '20 at 18:45
  • This is not related to the way you insert the code. The problem is that you use html attribute for the event so your function should be exposed globally e.g. `window.myFunction = function () { ..... }` but it's a bad solution generally so use addEventListener instead. – wOxxOm Aug 03 '20 at 19:48

1 Answers1

1
(function() {
    const myText = document.createElement("input"),
        demo = document.createElement("p"),
        button = document.createElement("button");
    myText.type = "text";
    myText.value = "Some text...";
    button.textContent = "Try it";
    button.addEventListener("click", () => demo.innerHTML = myText.value.replace(/\s{2,}/g, " "));
    document.body.insertAdjacentElement("beforeend", myText);
    document.body.insertAdjacentElement("beforeend", demo);
    document.body.insertAdjacentElement("beforeend", button);
})();
TimTIM Wong
  • 788
  • 5
  • 16