Off the Ridge Code Newsletter

Search

All posts in "ProTips"

jQuery – Pro Tip #3

Published January 24, 2015 in jQuery , ProTips - 1Comments

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/

jQuery – Pro Tip #1.

Published January 23, 2015 in jQuery , ProTips - 0Comments

jQuery – Pro Tip #1


1. Use CDN (content delivery network)
Go to: https://developers.google.com/speed/libraries/devguide
and pick a version of jQuery you’re interested in:
e.g.
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>

2. but don’t forget to fallback onto the local server in case the CDN isn’t available with:
<script> window.jQuery || document.write(“<script src=’js/jquery.js’></script>

3. putting it all together:

[[code style="color: black; word-wrap: normal;"]]czozMzY6XCIgJmx0O2h0bWwmZ3Q7ICA8YnIgLz4gJmx0O2hlYWQmZ3Q7ICAgPGJyIC8+ICAgJmx0O3NjcmlwdCBzcmM9XCIvL2FqYXgue1smKiZdfWdvb2dsZWFwaXMuY29tL2FqYXgvbGlicy9qcXVlcnkvMi4xLjMvanF1ZXJ5Lm1pbi5qc1wiJmx0Oy9zY3JpcHQmZ3Q7ICA8YnIgLz4ge1smKiZdfSAgJmx0O3NjcmlwdCZndDsgIDxiciAvPiAgICAgd2luZG93LmpRdWVyeSB8fCBkb2N1bWVudC53cml0ZShcIiZsdDtzY3JpcHQgc3Jje1smKiZdfT1cJ2pzL2pxdWVyeS5qc1wnJmd0OyZsdDsvc2NyaXB0Jmd0O1wiKTsgIDxiciAvPiAgICZsdDsvc2NyaXB0Jmd0OyAgPGJyIC8+ICZsdDt7WyYqJl19L2hlYWQmZ3Q7ICA8YnIgLz4gJmx0Oy9odG1sJmd0OyAgPGJyIC8+XCI7e1smKiZdfQ==[[/code]]