If I click on the first “Change”, I will receive console.log('click happend'). But if I add one of these fields through javascript (click "Add Field"), then Edit clickfrom this new window will not work. I know this because javascript is launched when there was no element and why there is no click event listener. I also know that with jQuery I could do this:
$('body').on('click', '.edit', function(){
and it will work.
But how can I do this with simple Javascript? I could not find a useful resource. Created a simple example that I would like to work on. What is the best way to solve this problem?
So, the problem is this: if you add a field and then click "Edit", nothing will happen.
var XXX = {};
XXX.ClickMe = function(element){
this.element = element;
onClick = function() {
console.log('click happend');
};
this.element.addEventListener('click', onClick.bind(this));
};
[...document.querySelectorAll('.edit')].forEach(
function (element, index) {
new XXX.ClickMe(element);
}
);
XXX.PrototypeTemplate = function(element) {
this.element = element;
var tmpl = this.element.getAttribute('data-prototype');
addBox = function() {
this.element.insertAdjacentHTML('beforebegin', tmpl);
};
this.element.addEventListener('click', addBox.bind(this));
};
[...document.querySelectorAll('[data-prototype]')].forEach(
function (element, index) {
new XXX.PrototypeTemplate(element);
}
);
[data-prototype] {
cursor: pointer;
}
<div class="box"><a class="edit" href="#">Edit</a></div>
<span data-prototype="<div class="box"><a class="edit" href="#">Edit</a></div>">Add box</span>
Hide resultJSFiddle
Q/A - , , . eventListener (s) new XXX.ClickMe(element); , DOM?