Search code examples
jqueryfunctionchainable

How do I make this into a chainable jquery function?


My function returns a filtered (array) list of items based on the data attribute.

I would like it if I could make this function chainable:

$(document).ready(function (){
    function filterSvcType (svcType) {
        var selectedServices = $("#service-list div");
        var chose = selectedServices.filter(function() {
            return $(this).data("service-type") ==  svcType;
        });

        console.log(chose);             
    }
    filterSvcType("hosting");       
});

What I want to do is call it like this:

filterSvcType("hosting").fadeOut(); 

How do I do this?


Solution

  • All you need to add is return chose; after your console.log call.

    But you could also turn this into a jQuery plugin

    (function($) {
        $.fn.filterServiceType = function(svcType){
           return this.filter(function(){
               return $(this).data("service-type") ==  svcType;
           });
        };
    })(jQuery);
    

    Then you can call as

    $('#service-list div').filterSvcType('hosting').fadeOut();
    

    Which is a bit more jQueryish.