0

When I click the button, it doesn't run the onclick. I tried it in the console and it worked fine. Can anyone help?

function customAlert(message) {
  sect = document.createElement("section");
  sect.className = "alert";
  sect.innerHTML = message + "<br /><br />";

  var but = document.createElement("button");
  but.innerHTML = "Gotcha.";
  but.onclick = "document.body.removeChild(sect);";

  sect.appendChild(but);
  document.body.appendChild(sect);

}
3
  • the value of onclick should be a function, not a string. Commented Nov 12, 2014 at 21:35
  • @scunliffe It can be a string, just like putting the attribute into HTML <button onclick="somestring">. But it will be executed in the global scope. Commented Nov 12, 2014 at 21:36
  • If it works in some cases... as a string... I consider that to be a fluke (and likely global due to an quick 'casting' to a function (e.g. eval()). From the docs its clear that it should be a function reference: developer.mozilla.org/en-US/docs/Web/API/… Commented Nov 12, 2014 at 21:41

1 Answer 1

3

You should use this syntax:

but.onclick = function () {
    document.body.removeChild(sect);
}

So, onClick is a property. This means that is has some value. When btn is clicked, javascript (the browser) calls this property, but it expects it to be a function, some code to be executed. Instead, it "sees" a string and does not know what to do with it.

Sign up to request clarification or add additional context in comments.

5 Comments

Please add an explanation of why the original syntax doesn't work and this does.
Added an explanation.
The explanation is not quite right. It knows what to do with a string, it executes it, as with eval(string). The reason it doesn't work is because variables are evaluated in the global scope, and he wants to access the local variable sect.
I created an online JS Fiddle test for this jsfiddle.net/g5hdfpa8/10 I don't think the string option works at all (at least in standards mode in Firefox, Chrome, Opera, IE10)
Thanks guys! I'm working on a little game and this helped a lot! <3 Stackoverflow! The community is comprised of the best people ever!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.