1

Possible Duplicate:
Why does jQuery or a DOM method such as `getElementById` not find the element?

This Event listener works on jsFiddle, but not when I call it from my PHP page.

function addDice() {  
 var add = document.getElementById("add");  
alert("test");      
}  

var el = document.getElementById("add");   
el.addEventListener("click", addDice, false);  

   <li id="add">CAll ADD</li>

I have the script in my index page between the <Script> tags, If I put an onclick="addDice" in the <li> tag it works, but not with the eventListener.

Community
  • 1
  • 1
Dymond
  • 2,040
  • 5
  • 37
  • 75
  • 6
    Probably you have `onLoad` selected from `Framework` field in jsFiddle, but your page tries to access `#add` before it exists. – Teemu Feb 02 '13 at 13:30
  • That is what i thought first, but how can I have an body onload without calling the function ? – Dymond Feb 02 '13 at 13:32
  • here's a simple, great example - toggle class of an element via a separate element: http://jsfiddle.net/UaT3P/115/ – zero_cool Aug 18 '14 at 19:32

2 Answers2

3

Try this:

window.onload = function () {
    function addDice() {  
        var add = document.getElementById("add");  
        alert("test");      
    }  
    var el = document.getElementById("add");   
    el.addEventListener("click", addDice, false);
}
Teemu
  • 21,017
  • 6
  • 49
  • 91
  • And there is magic.! Have been pulling my hair for a bit now. Thank you very much!. – Dymond Feb 02 '13 at 13:40
  • You've been working with IE5 quirks mode last five years??? :-S – Marcel Korpel Feb 02 '13 at 13:40
  • @MarcelKorpel Me? Yep, the intranet stuff in the company I was working for. Actually it seems I've to update my profile. A new job, no more IE Quirks, now I'm free to use IE8 : ). – Teemu Feb 02 '13 at 13:45
2

your code Run Before #add for That is not work You can solve it Like this

window.onload=function(){
         var el = document.getElementById("add");   
         el.addEventListener("click", addDice, false);
}

or by JQuery

jQuery(document).ready(function() {
         var el = document.getElementById("add");   
         el.addEventListener("click", addDice, false);

}) ; 
mohammad mohsenipur
  • 3,158
  • 2
  • 14
  • 22