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.

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

give examples please, otherwise this is best as a comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.