Saturday, January 24, 2015

jQuery - Pro Tip #3

Extend jQuery pseudo class

It's a little bit contrived example, but let's say I have an input group:

     <div class="form-group">
        <input class="form-control" type="text" name="name">
     </div>

and I'd like to do something to that input group, such as:

      $('.form-group').removeClass('has-error').addClass('has-success');

If I do it over and over again, I might consider wrapping it in a method:
 
       RemoveAddClass('.form-group');

function RemoveAddClass(selector){
    $( selector ).each(function() {
       $(this).removeClass('has-error').addClass('has-success');
    });    
};

and this is pretty good, however there's a better way, and that is extending jQuery pseudo class:

turning the above into:

$.extend($.expr[":"], {
    removeAddClass: function(element){     
        $(element).removeClass('has-success').addClass('has-error');
    }
});

you can check out my fiddle here: http://jsfiddle.net/seba368/osub4xw2/1/




No comments:

Post a Comment