5

I have a pop up window with a button. When I click the button I want something to happen, say an alert.

The issue I am having is that the onclick event fires as soon as the popup is launched and not when the button is clicked.

Here is the code. Any thoughts will be much appreciated.

var popup = open("", "Popup", "width=300,height=200");
var btn = popup.document.createElement("button");
btn.style.height = "50px";
btn.style.width = "150px";
popup.document.body.appendChild(btn);

btn.innerHTML="button1";
btn.onclick = alert("hello");
user3840170
  • 26,597
  • 4
  • 30
  • 62
RCW
  • 121
  • 2
  • 6

2 Answers2

15

In your code

btn.onclick = alert("hello");

onclick is not fired. Just alert is executed immediately. You should wrap it into a function:

btn.onclick = function(){ alert("hello");}
claustrofob
  • 5,448
  • 2
  • 19
  • 22
  • May I ask why is the first function being executed ? Looks like we are just assigning a function to the onclick event. – Ced Mar 27 '16 at 20:16
1

assign function to the btn.onclick event.

Guanxi
  • 3,103
  • 21
  • 38