callmekatootie
callmekatootie

Reputation: 11228

Event listener to dynamic HTML not working

Using a angularjs directive, I am adding an event listener to a dynamically created HTML element that is inserted into the DOM.

However, the event listener is not triggering. If I add an event listener to the document, it works but it does not seem to be calling the event listener associated with the dynamically added element.

I have created a fiddle for the issue: Fiddle.

I create the dynamic element as:

button = document.createElement('button');

I then add the event listener:

button.addEventListener('click', function () {
    alert("Button event listener is called");
});

But the event listener is never called.

EDIT: Please note that the directive will be used in multiple locations and I am looking for a solution that does not use classes or IDs but still must uniquely capture the clicks.

Upvotes: 3

Views: 833

Answers (2)

tasseKATT
tasseKATT

Reputation: 38490

Instead of:

element[0].insertAdjacentHTML('afterend', button.outerHTML);

Use:

element[0].insertAdjacentElement('afterend', button);

Demo: http://jsfiddle.net/7nus5/

Upvotes: 5

ndugger
ndugger

Reputation: 7531

I fixed it for you: http://jsfiddle.net/BBHzr/2/

var app = angular.module('Test', []);

app.directive('sampleDirective', function () {
    return function (scope, element, attrs) {
        var button = document.createElement('button');    

        //document.addEventListener('click', function () {
        //alert("Document Event Listener triggered");
        //});

        button.textContent = "Click Me!";

        element[0].insertAdjacentHTML('afterend', button.outerHTML);

        button = document.querySelector("button");

        button.addEventListener('click', function () {
            //This never gets called :(
            alert("Button Event Listener triggered");
        });

    };
});

You were referencing the creation of the button, and not actually the element on the page for the event listener -- or it was just the order of the code on the page. Either way, it works now.

Upvotes: 0

Related Questions