Kokodoko
Kokodoko

Reputation: 28128

Remove the click event from a single Div element

I have added a mousedown handler to all the divs inside a parent div, like this:

$productContainer.children(".button").on('mousedown', function(){
    var index = $(this).index();
    console.log("Clicked button at " + index);
    // this doesnt work
    $(this).removeAttr('mousedown');
});

Now I want to remove the mousedown handler after the button is clicked, for that particular div. How do I do that? Removing the attr mousedown doesn't seem to work.

Upvotes: 0

Views: 114

Answers (3)

Max Pro
Max Pro

Reputation: 58

instead of :

$(this).removeAttr('mousedown');

use :

$(this).unbind('mousedown');

or

$(this).off('mousedown');

Upvotes: 1

underscore
underscore

Reputation: 6877

use .off Description: Remove an event handler.

$productContainer.children(".button").off('mousedown');
$productContainer.children(".button").on('mousedown', function(){
    var index = $(this).index();
    console.log("Clicked button at " + index);
    // this doesnt work
    $(this).removeAttr('mousedown');
});

Upvotes: 1

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

Use the off method:

$productContainer.children(".button").on('mousedown', function(){
    var index = $(this).index();
    console.log("Clicked button at " + index);
    $(this).off('mousedown');
});

More info: http://api.jquery.com/off/

You could also use the one method instead. It will automatically remove your event handler at the first time it is triggered:

$productContainer.children(".button").one('mousedown', function(){
    var index = $(this).index();
    console.log("Clicked button at " + index);
});

More info: http://api.jquery.com/one/

Upvotes: 3

Related Questions