User
User

Reputation: 1662

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 ?

Upvotes: 0

Views: 56

Answers (1)

Geeky
Geeky

Reputation: 7488

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

Upvotes: 1

Related Questions