The button don't do the function

  • A+
Category:Languages

I've made a button using javascript, but the onClick event I've set does not seem work.

Here is my code:

function myFunction() {   console.log('button pressed') }  var BUTTON = document.createElement("button"); BUTTON.name = "not"; BUTTON.type = "button"; BUTTON.onclick = "myFunction()"; var textBUTTON = document.createTextNode("TEST"); BUTTON.appendChild(textBUTTON); var output = document.getElementById("test"); output.appendChild(BUTTON);
<div id="test"></div>

The button which is created by javascript appears, but the function, myFunction(), doesn't do anything.

If I make the button manually, with HTML, it works as expected

function myFunction() {   console.log('button pressed') }
<button name="not" type="button" onClick="myFunction()">TEST</button>

 


The issue is with this line:

BUTTON.onclick = "myFunction()"; 

It should be:

BUTTON.onclick = myFunction; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: