I would like to create a button using Javascript but why does the upB.onClick = testUp() not work?
<button onClick="testUp()">Up</button>
var upB = document.createElement('button');
upB.classList.add("up_btn");
upB.innerText = "Up";
upB.onClick = testUp();
CodePudding user response:
I would use upB.setAttribute('onclick','testUp()') ;
var upB = document.createElement('button');
upB.classList.add("up_btn");
upB.innerText = "Up";
upB.setAttribute('onclick','testUp()') ;
document.body.appendChild(upB);
function testUp(){alert('testUp')}
EDIT : following suggestion in comment, please see snippet below with addEventListener
.
var upB = document.createElement('button');
upB.classList.add("up_btn");
upB.innerText = "Up";
upB.addEventListener("click", testUp, false);
document.body.appendChild(upB);
function testUp(){alert('testUp')}
CodePudding user response:
#1
var upB = document.createElement('button');
upB.classList.add("up_btn");
upB.innerText = "Up";
upB.addEventListener("click", testUp);
Try This