Off the Ridge Code Newsletter


All posts in "jQuery"

jQuery – Pro Tip #4 – jQuery Difference between find and filter

Published January 26, 2015 in jQuery - 1Comments

jQuery Difference between find and filter

If I have a list of items such as:

<ul id=”tasks”>
    <li class=”task”>Do some work</li>
    <li class=”task”>Do more work</li>
    <li class=”relax”>Relax!</li>

and I’d like to select all list elements inside with class=”task” assigned.

I might want to do something like this:

// cache the result.
var $tasks = $(‘#tasks li’);

var $task = $tasks.find(‘.task’);

and that of course won’t work. The reason is this:

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

in other words it says: ‘search through all the child elements only’ and since we are already at the <li> level there’s nothing below it!

The solution to this is to use .filter() method that works on the currently matched elements.

var $task2 = $tasks.filter(‘.task’);

jsFiddle example:

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”>

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


If I do it over and over again, I might consider wrapping it in a method:

function RemoveAddClass(selector){
    $( selector ).each(function() {

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){     

you can check out my fiddle here:

jQuery – Pro Tip #2

Published January 23, 2015 in jQuery - 1Comments

jQuery – Pro Tip #2 – selector caching!

instead of repeating the selector and hence (re)traveling the DOM:

function doWork(){

cache the selector – caching it outside the method allows for reuse in multiple methods.
var someDivTag = $(‘#divTag’); 
function doWork(){

and finally chain it:
function doWork(){

jQuery – Pro Tip #1.

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

jQuery – Pro Tip #1

1. Use CDN (content delivery network)
Go to:
and pick a version of jQuery you’re interested in:
<script src=””></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]]

Starting with jQuery – Part 4

Published April 30, 2014 in jQuery - 0Comments

How to load html data from the server (Ajax style)

$(selector).load(url,data,callback) – loads data from the server and inserts the returned HTML into the DOM. 
The first parameter is mandatory, while the other two are optional.

1. Using just the first parameter: url.

2. Using the first two parameters: url and passing in JSON data.
     $(#FirstDiv).load(‘MyPage.html, {author:Homer});

3. Using the url and callback function:
        function(response, status, xhr){
          if(status == “error”){
         if(status == “success”){
             alert(“External content loaded successfully!”);


I’m including the sample files here. You can extract them and if you have IIS Express (usually comes with Visual Studio installation) you can run it without starting Visual Studio.

C:Program FilesIIS Express

and drop the files into the path pointed by the default website.

Good Luck!

Starting with jQuery – Part 3

Published April 26, 2014 in jQuery - 0Comments

Click here to download example file

– How to iterate over html nodes:

jQuery provides us with an each function – that can be used to iterate over any collection, whether it’s an object or a simple array. It iterates over DOM elements and passes current loop iteration starting with 0.

.each(function(index, Element))

There are two ways to iterate over the elements:

         alert(index + ‘=’ +$(this).text());


 $(‘div’).each(function(index, elem){
     alert(index + ‘=’ +$(elem).text());}

They both accomplish the same thing, the first one uses $(this), basically passing DOM element to jQuery so this refers to the current element.

–  How to modify DOM:, so to iterate through each div in the DOM tree and update the author node:

$(‘div’).each(function(i){ = “index= ” + i;});

Note: There’s a difference between $(this) and this:
1. $(this) – represents the jQuery object.
2. this – represents the raw javascript (DOM) object.

– How to modify attributes:

We can grab the author attribute using:

var result = $(‘#SomeDiv’).attr(‘author’);

If we want to modify the value of object’s attributes:


   this.title = ‘New Title’;});


     $(this).attr(“title”, ‘New Title’); });

The first example uses raw DOM javascript object (this.title), the second example, while accomplishing the same thing, uses jQuery object and accesses title via jQuery API.

Mousing over reveals the title:

Now, if we want to update multiple values (title, style, etc.) or attributes then we can harness the power of JSON (JavaScript Object Notation) 

  alt: ‘Richard Feynman’,
  width: ‘400’,
 style: ‘border: 1px solid red;’

jQuery supports what’s called a map – which is basically a JSON object with properties.

Note: the attributes above need to match the <img> attributes. 

JSON object is essentially an unordered collection of name/value pairs, self describing, easy to understand AND much faster to parse than XML – and yes, it is language independent.

The first object is delimited by the outside brackets {FirstName, LastName} – then inside we have another object that is part of the outside object – nested object with the Address:
     Street: ‘123 Nice St.’,
     City: ‘Chicago’,
     State: ‘IL’,
     Zip: 60606

You can do arrays: (the square bracket represents an array)
    { “FirstName”:”Jeane” , “LastName”:”Waterman” }, 
    { “FirstName“:”Dania” , “LastName“:”Dates” }, 
    { “FirstName“:”Tamie” , “LastName“:”Rost” }

    title: “Yet Another Title”,
    style: ‘font-size: 20pt; background-color:green;’ 


              title: ‘Yet Another Title’
     .css(‘title’,’Yet Another Title’)
     .css(‘font-size’, ’20pt’);

The second example uses chaining of the jQuery properties.

– How Insert and Remove Nodes:

1. append() – insert content to the end of element.
2. appendTo() – insert element to the end of the target.
3. prepend() – insert content to the beginning of element.
4. prependTo() – insert element to the beginning of the target.
5. remove() – remove elements from the DOM.

.append(‘<span style=”background-color:steelblue”>appended Child 1 Blue</span>’);  

.prepend(‘<span style=”background-color:steelblue”>prepended Child 2 Blue</span>’); 

To remove some rows from the table:


results in:


Click here to download example file.

Starting with jQuery – Part 2

Published April 24, 2014 in jQuery - 0Comments

What is selector in jQuery?

Selectors allow you to select elements on the page or in other words identify an HTML element on the page so that you can manipulate it with jQuery.
The basic syntax is:

jQuery(selector) or $(selector)

1. By Tag Name:

                  $(‘p’) – selects all <p> elements
                  $(‘a’) – selects all <a> elements
– reference multiple tags use comma, to separate the elements:
                $(‘a,p,div’) – selects all anchors, paragraphs and div elements.
– selecting descendants: 
      $(‘ancestor descendant’) – selects all descendants of the ancestor:
      $(‘table tr’) – selects all tr elements that are descendants of the table element
2. By ID:
   $(‘#myID’) – # hash tag indicates to jQuery that we’re looking for the ID.
3. By Class Name:
    $(‘.myClass’) – selects <p class=’myClass”>
Combining Tag Name with Class Name:
    $(‘a.myClass’) – selects only <a> tags with class “myClass”
Let’s apply some CSS to my html via jQuery.


<div class=”FirstDiv”>
    <br />
    <span class=”FirstDiv”>This is my First Span</span>
    <br />
    <div class=”SecondDiv”>
        <span>Second Div</span>


<script type=”text/javascript”>
                                  ‘border’:’2px dashed #fff’,
                                  ‘box-shadow’:’0 0 0 4px #ff0030, 2px 1px 6px 4px rgba(10, 10, 0, 0.5)’,
                                  ‘text-shadow’:’-1px -1px #aa3030′,


I’ve applied CSS only to my FirstDiv (or so I thought) but we can see that there’s a problem.
The issue here is my span and my div have the same class name. One solution would be to rename the span but we jQuery selectors we can be very specific and fix it by qualifying the selector to with div, i.e. div.FirstDiv

                                     ‘border’:’2px dashed #fff’,
                                     ‘box-shadow’:’0 0 0 4px #ff0030, 2px 1px 6px 4px rgba(10, 10, 0, 0.5)’,
                                     ‘text-shadow’:’-1px -1px #aa3030′,

Much better!

4. By Attributes:

To select by Attribute value we use brackets:
  1. $[‘a[author]] -> select all the anchor tags that have an author attribute.
  2. $[‘a[author=”charles dickens”]’) – select all anchor elements that have ‘charles dickens’ author attribute value.

 <div author=’charles dickens’>
    charles dickens

             var divs = $(‘div[author=”charles dickens”]’);


 5. By Input Nodes

$(‘:input’) – selects all form control. (e.g.input, textarea, button, image, etc)
$(‘:input[type=”button”]’) – selects all buttons on the page.

6. Additional selectors:

 1. :contains()
     $(‘div:contains(“dickens”)’) – selects div’s that contain the text (case-sensitive) “dickens”.
     as in:
    <div>charles dickens</div>

2. odd or even rows in a table
    e.g. $(‘tr:odd’) and $(‘tr:even’)

3. $(‘element:first-child’) – selects the first child of every element group:
       e.g. $(‘span:first-child’)
as in:
   <span>first child, first group</span>
   <span>second child, first group</span>
   <span>first child, second group</span>
   <span>second child, second group</span>
   <span>first child, third group</span>
   <span>second child, third group</span>

4. [attribute^=”value“] – selects the elements that begin with value.
 as in:
<input type=”button” value=”Process this stuff”/>
<input type=”button” value=”Process that stuff”/>

5. [attribute$=”value“] – selects the elements that end with value.
 as in:
<input type=”button” value=”Process this stuff“/>
<input type=”button” value=”Process that stuff“/>

5. [attribute*=”value“] – selects the elements that contains the value.
 as in:
<input type=”button” value=”Process this stuff“/>
<input type=”button” value=”Process that stuff“/>

You can download an example file to get you started.

Starting with jQuery – Part 1

Published April 24, 2014 in jQuery - 0Comments

How to start with jQuery?

1. Go to and download either jQuery 1.x if you’re planning on supporting older browsers (e.g. IE 6-8) or jQuery 2.x if you’d like more slimmer version that doesn’t have the overhead of supporting older versions and it’s much leaner. In other words jQuery 2.x is meant for IE 9 and higher.

You’ll find two different versions for each of the versions one with *.min and the other without the *.min. The *.min is a very condensed version of jQuery with all the whitespace removed and shortened variables and is generally meant for production. If you’re developing code and would like to be able to step through it, I recommend downloading one without the suffix .min.

2. Reference it in your page:

  <script type=”text/javascript” src=”jquery.js”></script>

Alternatively, you can use Content Delivery Network or CDN – either from Microsoft or Google 

 <script type=”text/javascript”

OR from Google:

<head><script src=””></script></head>

– We’re almost Ready()

When jQuery is loaded the window document or object gets a property called jQuery and that property is initialized IFF jQuery is loaded. i.e. window.jQuery.
You can either use window.jQuery or you can use the alias of it which is a $.
If you were going to peek at the jQuery source code at the end of the file you would find this line:

window.jQuery = window.$ = jQuery;

So to detect when the page is ‘ready’ (the DOM hierarchy is loaded) we can simply use:


              // do something useful here..

This is it for the first post.