Friday, February 01, 2013

Adding click event to button through Javascript using addEventListener


Adding button to DOM and futher adding click event to button through Javascript using addEventListener

<!DOCTYPE html>
<html>
<head>
<script>
function btnclick(person)
{
alert(person + " is free tomorrow!");
}


function load()
{
alert("Just one question...");
var s = document.getElementById("page-content");
var i = document.createElement("button");
i.innerHTML="myBtn";
s.appendChild(i);

if(i.addEventListener)

i.addEventListener('click',function (){btnclick("Vinayak");}, true);
}
 
}
</script>
</head>

<body onload="load()">
<div id="page-content"></div>
<p>Who is free from tomorrow?</p>
</body>
</html>

- Vishwajit Girdhari, .NET Enthusiast