Search code examples
jqueryjquery-callback

Passing jQuery's in-build functions as callback


Very often in jQuery I need to call for in-build function (hide, show, slideDown, etc) and usually we call them via anonymous wrap function:

$('button').click(function () {
  $('div').animate({
    opacity: 0.25
  }, 2000, function() { $(this).hide() })
})

Is there a way to pass these functions by reference like this?

$('button').click(function () {
  $('div').animate({
    opacity: 0.25
  }, 2000, $(this).hide)
})

I guess it's not possible due to way jQuery adds this functions to objects, but it would be nice if somebody can eloborate why the problem occurs.


Solution

  • It doesn't work the way you've tried it because the call to hide won't have the context of $(this). You can do it that way by binding the function you pass as a callback to the object it needs to be called on:

    $('button').click(function () {
        $('div').animate({
            opacity: 0.25
        }, 2000, $.fn.hide.bind($(this)));
    });
    

    Here's a working example.