sebbl.sche
sebbl.sche

Reputation: 321

replace dynamically onclick handler

I insert dynamically some images used as buttons and add an onClick event.

$("img.image_edit_customer").live("click", function() {
    // when clicking the edit image of a row
    $(this).manipulateCustomer("editRowCustomer", {
        scope : "#customer_tbody"
    });
});

Later I want to remove the onClick event from the image used as button.

$('img[class^="image_edit"]').live('click', function() {
    // do nothing from now on
    alert('edit');
});

Now, it always executes the old and the new handler.

UPDATE

If I'm using die('click');, I can still execute the onCLick event once.

Upvotes: 0

Views: 199

Answers (4)

adeneo
adeneo

Reputation: 318352

For jQuery 1.7+

To attach an event that runs only once and then removes itself:

$(document).one("click", "img.image_edit_customer", function() {
    $(this).manipulateCustomer("editRowCustomer", {
        scope : "#customer_tbody"
    });
});

To attach an event that can be remove at a later time:

$(document).on("click", "img.image_edit_customer", editRow);

To remove the event:

$(document).off("click", "img.image_edit_customer", editRow);

Function to attach and remove

function editRow(e) {
   $(e.target).manipulateCustomer("editRowCustomer", {
       scope : "#customer_tbody"
   });
}

Upvotes: 1

Tomm
Tomm

Reputation: 2142

Rather than unbinding or killing (aka die) the events for all matched elements, I'd mark the individual elements with a 'marker' class like so:

$("img.image_edit_customer").live("click", function() {
    if(!$(this).hasClass('clicked')) {
       $(this).addClass('clicked');
       $(this).manipulateCustomer("editRowCustomer", {
           scope : "#customer_tbody"
       });
    }
});

Upvotes: 0

Christofer Eliasson
Christofer Eliasson

Reputation: 33875

Since you use .live() to bind the event you need to use the .die() method to remove the event-handler:

$('img[class^="image_edit"]').die('click');

Notice

As of jQuery 1.7, it is recommended to use the .on() and .off() methods instead, to attach and de-attach event handlers.

Upvotes: 0

Adrian Iftode
Adrian Iftode

Reputation: 15683

Since you are attaching the events with live method, you need to use die method

http://api.jquery.com/die/

Upvotes: 2

Related Questions