0

I'm trying to assign an event listener to a dynamically loaded anchor tag. The facility is a straightforward suggest box that pops up underneath a text-box. First I assign a keyup listener to the search box:

$('.question').keyup(function(e) {
    if (e.which != 13) {
        self.suggest($(this).val());
    }
});

Then, the called function, self.suggest:

function suggest(text) {
    if (text.length > 0) {
        bkBtn.hide();
        waitImg.show();
        var d = document.createElement('div');
        d.className = 'suggest-box';
        var data = {}
        data.text = text;
        $.ajax({
            url: BASE_URL + '/urm8/suggest',
            type: 'POST',
            data: data,
            cache: false,
            success: function(markup) {
                waitImg.hide();
                if (markup.indexOf('##none##') != -1 || markup.length == 0) {
                    $(d).hide();
                }
                else {

                    $(d).append(markup);
                    $('.content').append(d);
                }
            },
            error: function(e) {
                waitImg.hide();
                alert('error');
                $('.content').html('');
                $('.content').append(e.responseText);
            }
        })   
    }
}

I assign this function on document load to the .suggest-link selector:

$('.suggest-link').live('click', function(e) {
    var answerID = $(this).attr('id');
    alert(id)
    self.updateBackStack();

    $(document).find('.suggest-box').remove();
    $('.content').blindRightToggle('fast', undefined, function() {
        self.appendAnswer(false, answerID);
    }); 
});

There's no alert fired here. I'm not sure how to attach event listeners in this way, a little help would be appreciated.

Also I'm using the latest stable jQuery as of 10 minutes ago.

Alex
  • 4,844
  • 7
  • 44
  • 58

1 Answers1

2

Use 'on' instead of 'live' and delegate the event handling to a parent element, e.g:

$('#parent').on("click", "#child", function() {});

See also:

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Community
  • 1
  • 1
Chamila Chulatunga
  • 4,856
  • 15
  • 17