I recently started playing around with javascript for fun. I worked myself through the most of w3schools tutorial (including jquery ofc).
The point where i got stuck is simply calling a function at a click of a button.
My code (edited to provide a Minimal, Complete, and Verifiable example)
$("#linkId1").on("click", function(){
setTimeout(function(){
function decryptText() {
alert( "decrypted!" );
}
$("tableId").append('<a id="decryptID" class="button">decrypt</a>');
$("#decryptID").on("click", decryptText);
}, 500);
});
HTML:
<a id="linkId1">firstLink</a>
<table>
<tbody>
<tr>
<td id="tableId">
<a id="button1" class="button"></a>
<a id="button2" class="button"></a>
</td>
</tr>
</tbody>
</table>
Here's what i've already tried:
- Different approaches to calling the function
Making the function decryptText() global or local
- Adding an
eventListener
to the button after creating it (because I read on another post that it's better to use theeventListener
than putting theonclick
attribute in the HTML-tag). ~I mixed basic js with jQuery methods here - BIG mistake.
The browser console does not give me any errors - when I changed to code a bit, I got: Reference Error: decryptText() not defined
S.
EDIT: I tried doing it all in jQuery only, the selectors and the event handling.
As you can see, I changed the example code to the beginning of a simple encrypt and decrypt script - the core problem still stays the same though.
Checking with Firefox' inspector tool, this time the element does not have any event bound to it.
A probably important piece of information is that the table you can see in the HTML does not exist before an onclick ajax handler
is called from the element #linkId1
and inserts the whole div containing the tables into the html.