Recursive functions and removeEventListener <p>I want to write a dynamic button creator. So I have the <code>html</code> file</p> <pre><code>&lt;body&gt; &lt;button id="0" type="button" onclick="create_button(0)"&gt;Create button 1&lt;/button&gt; &lt;/body&gt; </code></pre> <p>and <code>js</code> file which "simulates" proper action</p> <pre><code>var counter = 0; function create_button(n) { /*Shift up*/ for (i=counter; i&gt;n; i--) { document.getElementById(i).id = i+1; document.getElementById(i+1).innerHTML = i+1; }; /*Create new button*/ var new_button = document.createElement("Button"); new_button.innerHTML = n+1; new_button.type = "button"; new_button.id = n+1; function helper() { create_button(n+1); }; new_button.addEventListener('click', helper ); document.body.insertBefore(new_button,document.getElementById(n).nextSibling); counter++; }; </code></pre> <p>However <code>/*Shift up*/</code> part only changes <code>id</code> and <code>innerHTML</code> of buttons not the action of <code>click</code>. So in order to fix that I need to add in <code>/*Shift up*/</code> two lines which should work as</p> <pre><code>document.getElementById(i+1).addEventListener('click', helper(i+1) ); document.getElementById(i+1).removeEventListener('click', helper(i) ); </code></pre> <p>Clearly It will not work. Due to recursive nature of <code>create_button</code> function, I imagine that <code>helper</code> should be moved outside of <code>create_button</code>. But I have no idea how to do it.</p> <p><strong>Some additional info</strong> I simplified the code, but in practice buttons have some addition functions which depend on n. Let say that we also want to alert the position of the button. So we change helper to</p> <pre><code>function helper() { create_button(n+1); alert(n+1); }; </code></pre> <p>See in <a href="https://jsfiddle.net/o3Lsttyq/3/" rel="nofollow">https://jsfiddle.net/o3Lsttyq/3/</a> what alerts say. Click for example 1,1,3.</p>