Off the Ridge Code Newsletter

Search

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>
</ul>

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: http://api.jquery.com/find/

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: http://jsfiddle.net/seba368/gn8L204a/

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 #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(){
    $(‘#divTag’).addClass(“has-error”);
    $(‘#divTag’).slideUp();
}

cache the selector – caching it outside the method allows for reuse in multiple methods.
var someDivTag = $(‘#divTag’); 
function doWork(){
   someDivTag.addClass(“has-error”);
    someDivTag.slideUp();
}

and finally chain it:
function doWork(){
   someDivTag.addClass(“has-error”).slideUp();
}

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

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.
    $(#FirstDiv).load(‘MyPage.html);

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:
     $(#FirstDiv).load(‘MyPage.html,
        function(response, status, xhr){
          if(status == “error”){
              alert(xhr.statusText);
          }
         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:

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


OR

2.
 $(‘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:

this.property, so to iterate through each div in the DOM tree and update the author node:

$(‘div’).each(function(i){   this.author = “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:

$(“button”).click(function(){
  $(“img”).attr(“height”,”50″);});

$(‘div.FirstDiv,div.SecondDiv’).each(function(index){
   this.title = ‘New Title’;});

OR:

 $(‘div.FirstDiv,div.SecondDiv’).each(function(index){
     $(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) 

$(‘img’).attr({
  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:
{
 FirstName:’Jeane’,
 LastName:’Waterman’,
  Address:
  {
     Street: ‘123 Nice St.’,
     City: ‘Chicago’,
     State: ‘IL’,
     Zip: 60606
  }
}

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



  $(‘div.SecondDiv’).attr(
  {
    title: “Yet Another Title”,
    style: ‘font-size: 20pt; background-color:green;’ 
   });

OR

 $(‘div.SecondDiv’)
    .attr(
            {
              title: ‘Yet Another Title’
            }
           )
     .css(‘background-color’,’green’)
     .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.

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

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




To remove some rows from the table:

$(‘tbody.RowsToRemove’).remove();  

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)

Selecting:
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”
Example:
Let’s apply some CSS to my html via jQuery.

HTML:

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

jQuery:

<script type=”text/javascript”>
     
          $(document).ready(function()
          {
             $(‘.FirstDiv’).css({‘padding’:’20px’,
            ‘margin’:’10px’,
                                 ‘background’:’#ff0030′,
                                 ‘color’:’#fff’,
                                 ‘font-size’:’21px’,
                                  ‘font-weight’:’bold’,
                                  ‘line-height’:’1.3em’,
                                  ‘border’:’2px dashed #fff’,
                                  ‘border-radius’:’10px’,
                                  ‘box-shadow’:’0 0 0 4px #ff0030, 2px 1px 6px 4px rgba(10, 10, 0, 0.5)’,
                                  ‘text-shadow’:’-1px -1px #aa3030′,
                                  ‘font-weight’:’normal’});
                             
 
          });
       
      </script>

Result:

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

  $(‘div.FirstDiv’).css({‘padding’:’20px’,
                 ‘margin’:’10px’,
                                    ‘background’:’#ff0030′,
                                    ‘color’:’#fff’,
                                    ‘font-size’:’21px’,
                                    ‘font-weight’:’bold’,
                                    ‘line-height’:’1.3em’,
                                     ‘border’:’2px dashed #fff’,
                                     ‘border-radius’:’10px’,
                                     ‘box-shadow’:’0 0 0 4px #ff0030, 2px 1px 6px 4px rgba(10, 10, 0, 0.5)’,
                                     ‘text-shadow’:’-1px -1px #aa3030′,
                                     ‘font-weight’:’normal’});
Result:

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.

Example:
HTML:
 <div author=’charles dickens’>
    charles dickens
    </div>

jQuery:
   $(document).ready(function()
              {
             var divs = $(‘div[author=”charles dickens”]’);
             divs.css({‘background’:’red’});
              });

Result:

 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:
<div>
   <span>first child, first group</span>
   <span>second child, first group</span>
</div>
<div>
   <span>first child, second group</span>
   <span>second child, second group</span>
</div>
<div>
   <span>first child, third group</span>
   <span>second child, third group</span>
</div>
etc..

4. [attribute^=”value“] – selects the elements that begin with value.
  e.g.
    $(‘input[value^=”Process“/>
 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.
  e.g.
    $(‘input[value$=”stuff“/>
 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.
  e.g.
    $(‘input[value*=”stuff“/>
 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 http://jQuery.com 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:

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

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


<head>
 <script type=”text/javascript”
   src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.js“>
</script>
</head>

OR from Google:

<head><script src=”http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js”></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:

$(document).ready(function(){

              // do something useful here..
            });
          </script>

This is it for the first post.