Frank Kluytmans
Frank Kluytmans

Reputation: 543

How do I get an event listener to work on an element that is added to my html via javascript?

I'm adding some HTML to my document via javascript. I also add a button to my HTML via this javascript function. I want this button to have an event listener, but this doesn't seem to work on the element added with javascript. Is it possible to fix this?

my js:

$('#content-overview li').on('click',function(){

            // Clear previous videos
            $('.content-overview-row').remove();

            // Insert new video
            var vimeoId = $(this).data('vimeo');            
            var html = '<li class="content-overview-row"><div class="content-overview-video"><iframe src="http://player.vimeo.com/video/'+vimeoId+'" width="950" height="534"></iframe><a id="close-video"></a></div></li>';

            // Find end of row and insert detailed view
            var nextRow = $(this).nextAll('.first-in-row:first');

            if(nextRow.is('li')){
                nextRow.before(html);   
            }
            else{
                //last row
                if($(this).hasClass('first-in-row'))
                {
                    //first item clicked in last row
                    $(this).before(html);
                }
                else{
                    $(this).prevAll('.first-in-row:first').before(html);
                }
            }           

            return false;

            $('#close-video').click(function() {
                console.log("works");
            });
    });

close-video is the close button I am talking about.

Upvotes: 0

Views: 81

Answers (1)

billyonecan
billyonecan

Reputation: 20250

You need to bind the click event to an element which exists in the DOM when the page is loaded, and delegate the dynamically added element, like so:

$(document).on('click', '#close-video', function() {
   ...
});

You should change document for the element closest to your #close-video so that it doesn't have to bubble right up to the document.

Also, you're returning false; before the #close-video click handler, so that code would never be executed anyway. Move it outside of your #content-overview li click handler.

Upvotes: 2

Related Questions