mister32
mister32

Reputation: 59

How to bind an event to content loaded asynchronously?

This is my html:

<div class="mydiv" data-cid="1">
    <div class="mydiv2">
        <p>
            <b>Call this text...</b> 
        </p>
    </div>
</div>

I am binding this event handler:

$(".mydiv").on('longtap',function(e,data)
{
    cid = this.getAttribute('data-cid');
    message = $(this).html(); // I want only B-Tag like this.b...
    if(this.getAttribute('data-cid')) doit(......); 
});

My problem is that if I load later with AJAX, the long-click method does not work anymore

My AJAX:

$.ajax({
    url: 'ajax.php?file=chat&readline=1', 
    success: function(data)
    {
        $("#content").append(data);
    }
});

Upvotes: 0

Views: 174

Answers (2)

emanuelpoletto
emanuelpoletto

Reputation: 174

Assuming that mydiv2 is inside .mydiv, you can solve both problems like this:

$(document).on('longtap', '.mydiv', function(e, data) {
    cid = this.getAttribute('data-cid');
    message = $(this).html('<b>' + $(this).find('b').html() + '</b>');
    if (this.getAttribute('data-cid')) doit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mydiv" data-cid="1">
    <div class="mydiv2">
        <p>
            <b>Call this text...</b> 
        </p>
    </div>
</div>

This binds the longtap event to the document, so you can load more content via Ajax and the event will still be triggered properly.

Besides, this finds <b> to show just it, as you expected.

Upvotes: 2

AmericanUmlaut
AmericanUmlaut

Reputation: 2837

Your problem appears to be that you are binding an event handler to an element that does not yet exist on the page. The easiest way to handle a case like this is to use event delegation, which lets you bind to a parent element like the document that is on the page when the event is bound:

$(document).on('longtap', '.mydiv', function(e, data)
{
    cid = this.getAttribute('data-cid');
    message = $(this).html(); // I want only B-Tag like this.b...
    if(this.getAttribute('data-cid')) doit(......); 
});

This works because the event handler is bound to the document, which is of course always present, but the handler will only actually trigger if the event triggers on an element that matches the delegation selector (".mydiv" in this case).

Upvotes: 0

Related Questions