2

I was wondering how can I bind a click event to a element that will later be added trough ajax call. I know in jQuery you can do it like this:

$(document).on('click', '.ajax-loaded-element' function(){});

but I'm not using jQuery at this point. My idea is something like this, but that doesn't work if you call the same file twice (not sure if ill need that, but I would like to make it bulletproof).

bindAjaxBtn: function(selector, fnName) {
    let isBinded = false;
    document.addEventListener('click', function(e) {
        const btn = document.querySelector(selector);
        if(btn === e.target) {
            if(!isBinded) {
                btn.addEventListener('click', function() {
                    fnName();
                    isBinded = true;
                });
                btn.click();
            }
        }
    });
},

Any help would be appreciated. :)

zmuci
  • 518
  • 1
  • 5
  • 21

1 Answers1

0

Its very simple. You can try this one. This will help you.

document.getElementById('btn').setAttribute('onClick','myfunction()');
function myfunction(){
  alert('Button Clicked');
}
<button id="btn">Click Here</button>

Happy Coding.

Yash Parekh
  • 1,513
  • 2
  • 20
  • 31
  • No. With your code you dont bind event on parent node. You bind event on element that are not already on page (because ajax loaded). – Georgio Jan 23 '18 at 09:50