Reputation: 14296
This is the piece of code in question:
...
var btnClick = document.getElementById("button");
btnClick .addEventListener("click", func, false);
}
function func()
{
alert("This works");
}
I don't get any alert box. See any problems?
Upvotes: 0
Views: 254
Reputation: 13729
Never use very generic terms such as 'button' as they tend to be reserved and you'll end up ripping your hair out if you're absolutely sure it should work. Use descriptive values for id attributes such as 'form_4_button_submit'.
Also an example of how to do cross-browser event handling...
if (window.addEventListener) {document.addEventListener('keydown',keyPressed,false);}
else {document.attachEvent('onkeydown',keyPressed);}
function keyPressed(evt)
{
var e = evt || event;
var key = e.which || e.keyCode;
switch (key)
{
case 77:// M
alert('m key pressed');
break;
case 76://L
alert('L key pressed');
break;
}
}
Upvotes: 0
Reputation: 707318
If you do all of the following, this will work:
addEventListener
(old versions of IE don't support that).id="button"
.btnClick
before .addEventListener
.You can see it work here: http://jsfiddle.net/jfriend00/HQ24Z/
Upvotes: 0
Reputation: 150030
Which browser are you using? IE doesn't support .addEventListener()
until version 9, so you need to say something like this:
var btnClick = document.getElementById("button");
if (btnClick.addEventListener){
btnClick.addEventListener('click', func, false);
} else if (btnClick.attachEvent){
btnClick.attachEvent('onclick', func);
}
// and if you're really keen:
else {
btnClick.onclick = func;
}
And don't use .getElementById()
on an element that hasn't been parsed yet, i.e., put the above code either in a document.ready or load event handler, or put it after the element in the page source.
Upvotes: 1
Reputation: 323
Its because of the reason that you have not initialised it....!!!
window.onload = prepareButton;
function prepareButton()
{
document.getElementById('button').onclick = function()
{
alert('you clicked me!');
}
}
Upvotes: 0