17

When I run the following script, the event always fires on page load. I am not sure what I am doing wrong here, I create the element, find it in the DOM then attach a listener, but it always fires the event when the page loads and not when the element is clicked.

<script type="text/javascript" language="javascript">
    document.write("<div id=\"myDiv\">I am a div</div>");
    el = document.getElementById("myDiv");
    el.addEventListener("click", alert("clicktrack"), false);
</script>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Russ Bradberry
  • 10,705
  • 17
  • 69
  • 85

2 Answers2

43
el.addEventListener("click", alert("clicktrack"), false);

When this line is executed, the alert will be called and return undefined. To pass the alert code you need to wrap it in a function.

el.addEventListener("click", function() { alert("clicktrack"); }, false);
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1

How about:

<script type="text/javascript" language="javascript">
  document.write("<div id=\"myDiv\">I am a div</div>");
  el = document.getElementById("myDiv");
  el.addEventListener("click", function() { alert("clicktrack"); }, false);
</script>
Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79