Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "addEventListener" Event Fires on Page Load [duplicate]

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>
like image 990
Russ Bradberry Avatar asked Mar 03 '10 18:03

Russ Bradberry


2 Answers

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);
like image 92
kennytm Avatar answered Sep 19 '22 15:09

kennytm


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>
like image 26
Sani Singh Huttunen Avatar answered Sep 16 '22 15:09

Sani Singh Huttunen