Search code examples
jquerylive

Jquery .live issue


I have the following snippet of code.

HTML (simplified):

    <tr>
    <td><div id="insert_24" class="insert">Invoegen</div></td>
    </tr>

On which a JS function is running (simplified) to retrieve the data from the form, add it to the database and then update the form/table with the correct class & ID's:

    $(".insert").click(function() {
        // current field, is the id: insert_24
        // layer is retrieved in the function: 24
        // Full table has the id 'canvas'

        // do something
        // Insert into database

        console.log('insert-'+layer);
        $("#"+ current_field).removeClass("insert").addClass("delete").html('delete').attr('id', 'delete_'+layer);
        $("table#canvas tr:last").attr('id', 'row_'+layer);
    });

Directly after this code I also have the code to delete a line (simplified):

    $(".delete").live("click", function() {
        // do something
        // Insert into database

        console.log('delete-'+layer);
        $("#row_"+ layer).remove();         
    });

The insert works perfectly, but when I look at the console log functions, on 'insert', also the 'delete' function is being triggered directly after the insert, which doesn't make sense. I only clicked the <div> once.

Which step/setting am I missing to have this function work in the correct way?


Solution

  • Update your click() handler to return false;, or:

    $(".insert").click(function(e) {
        e.stopPropagation();
        // your code here
    });
    

    .live() works by attaching a handler at the document level and waiting for events to bubble up - at which time it checks if the original target element matches the selector you used. So when a click occurs it first triggers the (non-live) click handler and then bubbles up to trigger the live handler.

    Note also that removing the "insert" class from the element will not stop your click handler from firing on that element. You'd need to either unbind the click handler (from within the handler) or change that one to a live handler too.

    Note that .live() is way out of date. You should update to use the delegated syntax of the .on() method instead..