Passing true / false to slideToggle()

It can be shimmed in like so:

;(function($) {
    var slideToggleOrig = $.fn.slideToggle;
    $.fn.slideToggle = function(display) {
        var fn,
            args = arguments;
        if ('boolean' != typeof display) {
            fn = slideToggleOrig;
        }
        else {
            if (display) {
                fn = this.slideDown;
            }
            else {
                fn = this.slideUp;
            }
            args = Array.prototype.slice.call(args, 1);// hide the extra arg from official functions
        }
        return fn.apply(this, args);
    };
})(jQuery);

This works by detecting if the first argument to slideToggle is a boolean (not just truthy/falsy) and, if so, substituting the up and down functions which have compatible signatures. This means you can use any existing signature, but add an extra argument at the start. It also chains correctly without modifying the stack or creating a new object.


It is simple like this:

$.fn.slideToggleBool = function(bool, options) {
  return bool? $(this).slideDown(options) : $(this).slideUp(options);
}

Enjoy!


slideToggle optionally takes 2 parameters duration and a callback so passing true/false to show/hide will not work. You might have to write your own plugin which will implement this logic. Something like this

$.fn.mySllideToggle = function(show){
   if(show){
      $(this).slideDown();
   }
   else{
      $(this).slideUp();
   }
}

Tags:

Jquery