9

I was making a script that creates div elements each time a button is pressed. Originally I had the function called inline with the onclick attribute, but jslint doesn't like that so I moved it out and instead tried to use addEventListener("click",function());

I've never used addEventListener() before so I'm not even sure I am using it correctly.

The problem is that it creates one div when the page loads and won't do anything when the button is pressed.

Thank you in advance.

here is what I have:

<body>
<form>
    <textarea id="a"></textarea>    
    <br>
    <input value="button" type="button">
</form>
<div id="content">
</div>
<script>
    /*jslint browser:true */
    function createEntry(text) {
        "use strict";

        var div = document.createElement("div");
        div.setAttribute("class", "test");
        document.getElementById("content").appendChild(div);
    }
    var input = document.getElementsByTagName("input")[0];
    input.addEventListener("click", createEntry(document.getElementById('a').value));
</script>

Kyle Messner
  • 111
  • 1
  • 1
  • 6

3 Answers3

13

Change the event listener like this

input.addEventListener("click", function(){
    createEntry(document.getElementById('a').value);
});

as it stands, you're passing the result of createEntry as an event listener, not the function itself

More information here:

https://developer.mozilla.org/en/docs/DOM/element.addEventListener

lostsource
  • 21,070
  • 8
  • 66
  • 88
7

Change this line

input.addEventListener("click", createEntry(document.getElementById('a').value));

into

input.addEventListener("click", function(){
createEntry(document.getElementById('a').value);
});
chtenb
  • 14,924
  • 14
  • 78
  • 116
4

Try using a JavaScript library like jQuery for event handling and DOM manipulation, to be browser safe and for uniformity.

You can use the event handlers in jQuery like the following:

$(<element_selector>).on("click", function (event) {
     // your code here...
});
Rakesh Menon
  • 166
  • 7
  • 3
    I knew how to do it with JQuery, but I wanted to improve my Javascript skills by writing without it. You bring up a good point about cross browser safety, though. Thanks :] – Kyle Messner Dec 07 '12 at 21:22