AAA
AAA

Reputation: 3

Dynamically created a button doesn't call the function when I deploy it on the server

I'm generating a button on the fly as such:

    var copyBtn = document.createElement("button");

    // Set the content of the new element
    copyBtn.innerHTML = "Copy to clipboard";

    copyBtn.setAttribute("onclick", "copyToClipboard();");
    //copyBtn.style.color = "red";
    copyBtn.style.fontSize = "20px";
    copyBtn.style.id = "copyBtn"
    copyBtn.style.className = "main-copyBtn";

and I've defined the function in my js file as:

function copyToClipboard() {
  //do something
}

When I run the page locally, it works. However, when I deploy it on the server, it tells me that the function is not found. What am I missing?

I expect the function to be found.

Upvotes: 0

Views: 29

Answers (1)

Unmitigated
Unmitigated

Reputation: 89274

Use addEventListener instead to avoid relying on the function being in the global scope.

copyBtn.addEventListener('click', copyToClipboard);

Upvotes: 2

Related Questions