Bohdan Vorona
Bohdan Vorona

Reputation: 725

bind() and unbind() in click() function

I have this code:

$('#people_nav>.prev, #people_nav>.next').click(function(){

   // Here I need to disable event of click for needed elements, see code below
   $('#people_nav>.prev, #people_nav>.next').unbind('click');

   ...
   code
   ...

   // Here I need resume event for click() function. How?

});

How can I resume event for click() function? It should be in body of click(function(){...});...

Upvotes: 0

Views: 163

Answers (3)

Somnath Kharat
Somnath Kharat

Reputation: 3600

You just need to use off

$('#people_nav>.prev, #people_nav>.next').off('click');

If jquery version >= 1.7 prefer on and off methods instead of bind and unbind methods

Upvotes: 0

adeneo
adeneo

Reputation: 318182

You can use on() and off() for that, and a named function

var elements = $('#people_nav > .prev, #people_nav > .next');

elements.on('click', doStuff); // bind handler

function doStuff() {

    elements.off('click');  // unbind handler

    /*...
    code
    ...*/

    elements.on('click', doStuff);  // rebind handler
});

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use a named function. Something like

var element = $('#people_nav>.prev, #people_nav>.next'); //cache for better performance
var yourFunction = function () {
    // Here I need to disable event of click for needed elements, see code below
    element.off('click'); //unbind event
        ...
    code
        ...
    // Here I need resume event for click() function. How?
    element.click(yourFunction);
};
element.click(yourFunction);

However, I would recommend the use of on() and off()

Upvotes: 0

Related Questions