antonpug
antonpug

Reputation: 14296

Javascript not responding to element click?

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

Answers (4)

John
John

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

jfriend00
jfriend00

Reputation: 707318

If you do all of the following, this will work:

  1. Wait for the document to load before trying to install the event listener. You can either run this code in a window.onload handler or place the javascript initialization code at the end of the body. You can verify if this is or isn't working by seeing if btnClick is valid or null.
  2. Only run this code in newer browsers that support addEventListener (old versions of IE don't support that).
  3. Make sure there is one and only one element in the page with id="button".
  4. Make sure there are no javascript errors in your page causing your script to stop running.
  5. Remove the space after btnClick before .addEventListener.

You can see it work here: http://jsfiddle.net/jfriend00/HQ24Z/

Upvotes: 0

nnnnnn
nnnnnn

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

vinay
vinay

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

Related Questions