0

When I click on the link it's working perfectly but only ONCE.

I want to be able to be able to keep the addEventListener even after it's been executed.

<div id=myBox>
    <a href="#" id="append">append</a>
</div>
document.getElementById("append").addEventListener("click", appendMore);
function appendMore() {
    myBox.innerHTML += '1';
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
davidmarko
  • 343
  • 3
  • 17

3 Answers3

4

You'll want to use a separate element to insert your content into.

document.getElementById("append").addEventListener("click", appendMore);

function appendMore() {
  tgt.innerHTML += "1";
}
<div id=myBox>
  <a href="#" id="append">append</a>
  <span id="tgt"></span>
</div>
Etheryte
  • 24,589
  • 11
  • 71
  • 116
  • 1
    Please, do not use innerHTML. This causes so many bugs it's not worth it. – Eraden Feb 02 '15 at 09:53
  • @Eraden So what's the alternative ? – davidmarko Feb 02 '15 at 09:56
  • 1
    `innerHTML` isn't inherently evil, but it has it's gotchas. Using it if you're aware of what you're doing has no downsides. See [this question](http://stackoverflow.com/questions/7476638/if-people-recommend-i-shouldnt-use-innerhtml-what-then-should-i-instead-use) for further discussion, for example. – Etheryte Feb 02 '15 at 09:58
  • That's like saying we should use screwdrivers to hit nails because occasionally people hurt themselves with hammers. – Etheryte Feb 02 '15 at 10:03
  • @Nit - A more accurate analogy would be "If you're going to use a hammer, make sure you understand how it can hurt you, and get trained up before going full steam ahead" – Jamiec Feb 02 '15 at 10:06
  • If you say so you probably know what is the best. From my experience this is simply evil part of DOM like eval is evil part of JS. jQuery is simplest, most secure way but people downvote it, why? – Eraden Feb 02 '15 at 10:07
  • @Eraden Because it's suggesting loading up an 85KB library for something that vanilla Javascript can do just as easily, with less clutter attached. – Etheryte Feb 02 '15 at 10:10
1
// Parent element
var el = document.querySelector('#myBox');
// Find append and add listener
el.querySelector("#append").addEventListener("click",appendMore);

function appendMore( event ) {
    // Append new text node
    el.appendChild( document.createTextNode('1') );
}
Eraden
  • 2,818
  • 1
  • 19
  • 17
-1

It would be achieved easily by using jQuery.

$('#append').click(function () {
    $('#myBox').append('1');
});

find this JSFIDDLE

NB: Please let us know if you want to achieve this using just plain javascript.

Sameer Azazi
  • 1,503
  • 10
  • 16