javascript - onclick() requires two clicks to trigger event <p>My problem is that when <code>onclick()</code> is triggered the first time, nothing happens, but when it is clicked a second time, the code is executed.</p> <p>The <code>onclick()</code> should turn the <code>&lt;div&gt;</code> into a png image file and save it to the computer.</p> <p>HTML (the TableDay function refers to a function I wrote which basically makes it easier to create the table):</p> <pre><code>&lt;div id="TableDiv"&gt; &lt;table id="Table"&gt; &lt;tr&gt; &lt;th&gt;Dag\Uur&lt;/th&gt;&lt;th&gt;1&lt;/th&gt;&lt;th&gt;2&lt;/th&gt;&lt;th&gt;3&lt;/th&gt;&lt;th&gt;4&lt;/th&gt;&lt;th&gt;5&lt;/th&gt;&lt;th&gt;6&lt;/th&gt;&lt;th&gt;7&lt;/th&gt;&lt;th&gt;8&lt;/th&gt;&lt;th&gt;9&lt;/th&gt; &lt;/tr&gt; &lt;?php TableDay("Maandag",1); TableDay("Dinsdag",10); TableDay("Woensdag",19); TableDay("Donderdag",28); TableDay("Vrijdag",37); ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;a id="Image" href="##" onclick="printTable()"&gt;Download&lt;/a&gt; </code></pre> <p>(Text is Dutch)</p> <p>The <code>onclick="printTable()"</code> refers to the following Javascript code:</p> <pre><code>&lt;script&gt; var element = $("#TableDiv"); // global variable var getCanvas; // global variable function printTable() { html2canvas(element, { onrendered: function (canvas) { getCanvas = canvas; }}); var imgageData = getCanvas.toDataURL("image/png"); // Now browser starts downloading it instead of just showing it var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream"); $("#Image").attr("download", "Rooster.png").attr("href", newData); } &lt;/script&gt; </code></pre> <p>What is happening exactly and how can I make it so that the <code>&lt;a&gt;</code> reference in the html code only needs to be clicked once?</p>