Wefa
Wefa

Reputation: 31

Jquery disable mousedown event without losing the function associated to the event

I'm trying to disable a mousedown event for an element and then enable it without redifining the function related to the event. When I do $(this).off(mousedownEvent) the event related is lost and I don't want to enable it with $(this).on(mousedownEvent, function()). Is there a way to do so?

Upvotes: 1

Views: 2602

Answers (2)

adeneo
adeneo

Reputation: 318162

Couldn't you just use an external function ?

function doStuffOnMouseDown(evt) {
    console.log('stuff happens here');
}

/* ENABLE */
$(this).on('mousedown', doStuffOnMouseDown);

/* DISABLE */
$(this).off('mousedown', doStuffOnMouseDown);

/* RE-ENABLE */
$(this).on('mousedown', doStuffOnMouseDown); // no suprise, it's just the same ?

That's pretty much the way to add and remove events without having to redefine the entire function body

Upvotes: 3

Get Off My Lawn
Get Off My Lawn

Reputation: 36291

The easiest way it my opinion is to create the function then reference the function like this:

function myMouseEvent() {
    // Do some stuff
}

You then just pass the reference of the function to the method like this:

$(this).off('mousedown', myMouseEvent);
$(this).on('mousedown', myMouseEvent);

Upvotes: 0

Related Questions