I am having trouble with the jQuery $ onclick event
by onclick i mean:
const $trigger = $('<button class="button primary" onclick="callback()">');
but for some reason, the callback is not "calling"
here is some example code (simplified)
$(function() {
const $add = $('.add-item');
const $container = $('.container');
$add.click(() => {
function callback() { // here is the error (not defined)
console.log(privateData); // but obviously this is defined...
}
const $item = $(`<li class="button" onclick="callback()">Click Me</li>`);
$container.append($item);
});
});
* {
box-sizing: border-box;
font-family: Roboto;
}
ul, li {
margin: 0;
padding: 0;
}
ul {
margin-top: 20px;
}
body, html {
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
}
.button {
list-style: none;
padding: 10px 20px;
background: #2980b9;
border-radius: 8px;
cursor: pointer;
color: #fff;
}
.button.primary {
background: #c0392b;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a class="button primary add-item">Add Item</a>
<ul class="container"></ul>
</div>
note that the only thing in the demo that matters is the javascript, which produces the following error:
{
"message": "Uncaught ReferenceError: callback is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 1,
"colno": 1
}
any helpz?