Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick event fires before button clicked - javascript

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");
like image 872
RCW Avatar asked Jun 27 '13 19:06

RCW


2 Answers

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");}
like image 153
claustrofob Avatar answered Sep 28 '22 18:09

claustrofob


assign function to the btn.onclick event.

like image 40
Guanxi Avatar answered Sep 28 '22 20:09

Guanxi