Question

I have this snippet of code and the Ajax call works grand and displays grand, my issue is how can I get vote click to work with the data loaded via the ajax call into #existingComments as the ajax call is firing on page load?

<script>
$(function() {
    var vData = {aid:2,rid:2};

    $.ajax(
    {
        url : "ajax.php",
        type: "POST",
        data : vData,
        success: function(data, textStatus, jqXHR)
        {
            $("#existingComments").html(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            $("#existingComments").html("");
        }
    });

    // Disable links on vote buttons
    $(".vote").on("click", "a", function(e) {
        e.preventDefault();
        alert('yup');
    });
});
</script>

Code snippet of whats loaded into #existingComments:

<div class="comment">
    <div data-cid="1" class="vote">
        <a title="+1 Vote" href="#"><span class="upVote">&nbsp;</span></a>
    </div>
</div>
Was it helpful?

Solution

The problem is that you are binding your delegated event to a dynamic element that does not exist until after your AJAX response comes back. You should bind your event to the container div instead.

Here's an example:

$("#existingComments").on("click", ".vote a", function(e) {
        e.preventDefault();
        alert('yup');
 });

fiddle

OTHER TIPS

Use:

$(document).on("click", ".vote a", function(e) {
            e.preventDefault();
            alert('yup');
        });

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top