User User - 1 month ago 6
Javascript Question

Onclick event triggerd in onload

I create dynamic button in onload function.The button was created but the alertfunc also call onload.

but I set the onclick event to trigger the alertfunc

window.onload = function () {
var body1 = document.getElementsByTagName("body")[0];
var btn = document.createElement("BUTTON");
var t = document.createTextNode("Click Here");
btn.appendChild(t);
btn.setAttribute("class", "button");
btn.setAttribute("id", "btnAssign");
btn.setAttribute("name", "btnAssign");
btn.setAttribute("onclick", "alertfunc()");
body1.appendChild(btn);
}

func alertfunc()
{
alert('test');
}


How can I prevent the alertfunc call onload ?

Answer

Make these changes to your code

window.onload = function() {
  var body1 = document.getElementsByTagName("body")[0];
  var btn = document.createElement("BUTTON");
  var t = document.createTextNode("Click Here");
  btn.appendChild(t);
  btn.setAttribute("class", "button");
  btn.setAttribute("id", "btnAssign");
  btn.setAttribute("name", "btnAssign");
  btn.addEventListener("click", alertfunc);
  body1.appendChild(btn);
}

function alertfunc() {
  alert('test');
}

Hope this helps

Comments