Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reattach an event to a new loaded DOM element with ajax

My problem is that my click callback function only works once and it has propably something to do with the fact that after the first callback, parts of my page will be refreshed with ajax actions. But how can i reattach the event to the new loaded DOM-Elements?

this is my function:

// DELETE ENTRY
    $('.delete').on('click', function(){
        //// ADDING DATA-INDEX TO ENTRIES ////

        $('.id').each(function(index){
            var id = $(this).html();
            var dataIndex = $(this).attr("data-index", id);
        });

        alert('clicked');

        var action = '_includes/deleteEntry.php';
        var method = 'post';
        var entryId = $(this).siblings('.id').attr('data-index');
        var entryIdNumber = entryId.substr(entryId.length - 2);

        var data = {'id' : entryIdNumber};

        $.ajax({
            url: action,
            type: method,
            data: data

        }).done(function(data){
            $('.main').empty();
            $('.main').append(data);
            return;
        });
    });
like image 692
Marten Zander Avatar asked Dec 24 '22 23:12

Marten Zander


1 Answers

Use a delegated event handler attached to a non-changing ancestor:

$(document).on('click', '.delete', function(){

This works by listening for an event (click) to bubble up to the ancestor, then it applies the jQuery selector, then it applies the function to any matching elements that caused the event. It also only connects a single handler to a single element, so is often faster to startup (if you have mutilple matches). The minuscule delay a delegated handler adds at event time will never be noticed as you simply cannot click that fast :)

The upshot of this is that the matching elements do not need to exist at event registration time, just when the event occurs so it is perfect for items that change dynamically.

document is the default if nothing else is closer to the changing elements. Never use body as the default for delegated mouse events as styling can cause it to not respond to mouse events (if it winds up with a calculated height of 0, so best to be safe).

like image 145
Gone Coding Avatar answered Jan 13 '23 14:01

Gone Coding