Introduction to jQuery (Part 1)

The way we build modern web applications has made a massive shift to client-side focus, with much of work written in javascript these days. So, JavaScript is a must one, but this does not necessarily mean that you have to stick with native JavaScript for your daily purpose and at this point I would like to mention two reasons for this. The first one is that conventional JavaScript requires more coding which could exclusively slow down project completion time significantly and the second one is that while developing custom features with native javascript, developers has to deal with browser compatibility issue which is just an extra overhead problem to deal with.

So, the convenient solution of this problem is to use a javaScript framework that could handle these two issues successively. One of the many available javaScript library the one that I have chosen is jQuery for its simplicity.

So, What is jQuery?

jquery

jQuery is a lightweight, fast feature-rich javascript framework which has been optimized to work with a variety of browsers automatically. It uses CSS selector style syntax to fetch elements in document object model (DOM) and wrapped those element set with jQuery functions for further manipulation.

How to integrate it in your project?

There are actually two ways you can integrate jQuery in your project.

  1. Using the CDN(Content Delivery Network) link
  2. By self hosting.

My personal preference is to go with the CDN link. Reason is given below:

  • Whenever a user browse a particular webpage, the browser cache some resources(e.g. JavaScript, CSS, Image etc) for further use. If you are using any of the popular CDN links chances are that their(user) browser might not need to load jQuery framework once again as the jQuery framework (and of course other resources) might be already in cache. This process ensures a better user experience in terms of speed. Please note that browser loads only those files that are new or modified and is not available in the browser cache or history. In brief, whenever any user browses your webpage and you are also using same CDNs file, the older cached version of jQuery file will be used.

Besides that, CDN’s will make sure that once a user requests a file from it, it’s served from the server closest to them, so your European users won’t have to get the file all the way from Asia. Use of CDN decrease the latency and shorter the connection distance.

With a CDN, users from a European point of origin will be able to download your site's static content faster from a closer server node.

With a CDN, users from a European point of origin will be able to download your site’s static content faster from a closer server node.

CDN LINK:

Loading CDN hosted jQuery is just like loading it locally, minus the part where you have jQuery stored on your hard drive, of course. Simply add the CDN link as the same way you used to refer any other external links. Google, Microsoft, jQuery team are kind enough to host the jQuery framework for you , I recommend you to use their CDN links since their hosted version are reliable, stable and most up to date.

snippet:

  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

At the time of this writing google is hosting the following version: 2.1.1, 2.1.0, 2.0.3, 2.0.2, 2.0.1, 2.0.0, 1.11.1, 1.11.0, 1.10.2, 1.10.1, 1.10.0, 1.9.1, 1.9.0, 1.8.3, 1.8.2, 1.8.1, 1.8.0, 1.7.2, 1.7.1, 1.7.0, 1.6.4, 1.6.3, 1.6.2, 1.6.1, 1.6.0, 1.5.2, 1.5.1, 1.5.0, 1.4.4, 1.4.3, 1.4.2, 1.4.1, 1.4.0, 1.3.2, 1.3.1, 1.3.0, 1.2.6, 1.2.3

Note: 1.2.5 and 1.2.4 are not hosted due to their short and unstable lives in the wild.

You can always get the update links on this link.

In terms of functionality, there is no difference between the jQuery-x.x.x.js and jQuery-x.x.x-min.js (also called minified version). However, this can play a vital role in the performance of the web page. The minified, compressed version takes up the least amount of space which is good from users side. But when your website is in testing/development condition you should use the non-minified version so that in case if you run into an error, you can actually see where in jQuery the problem actually happens.

Now that I have convinced you to use the CDN link to reference the  jQuery framework lets fix our main vision i.e. -“Write Less, Do More” . So, what I actually mean by that? Well,  in this section our main target is to write less code and achieve our desired functionality with the help of jQuery. This is a very simple concept that can be divide in two parts for further clarification.

  1. Find Something
  2. Do Something

1. Find Something: So, the main goal in this section is to find something, more specifically the DOM elements in which we do our desired manipulation. Comparing the native javascript code in jQuery finding the desired elements is less painful then anything. Before we go any further we must have a clear concept of what DOM actually is. So, lets have a look it first.

DOM: The DOM (Document Object Model)  is the way Javascript sees its containing pages’ data. Although HTML is used to build the DOM which is an in-memory representation of the page but its not actually the HTML you write your day to day life.

DOM0

Its also not the content that you find in the ‘View Source’ file.

DOM1

The only way you could  see DOM elements is through the Developers tool that ships with the browser. and I think thats the best possible way the DOM could be visualized.

DOM3
Now that we at least know what DOM is, the next target is to select the desired element in the DOM.  We could use the CSS selector and pass it to the  jQuery function that ships with the jQuery library to select the desired element.

The following section, examples are build on each other. So, you should read/practice them in order.

Now we will write jQuery code to select all the ‘p’ elements.

 jQuery('p');

In order to select a particular element pass it to the jQuery function. In the above example we passed the ‘p’ element to select it.

In JavaScript the sign $ actually has no special meaning like it has in other languages like PHP. So, the jQuery team used the $ sign to refer the jQuery function. Of course $  is just a shorter, more convenient name as well. If you ever take a look at the end of the the jQuery source file you will find following statement :

//Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

The inside story is that when you call the $() function and pass a selector to it, you are actually creating a new jQuery object. In JavaScript, functions are objects too, so that means that $ (and jQuery, of course) has properties and methods as well. For this reason you can call property and method of $. As an example we can refer to the $.support property to find out what the current browser environment supports and  use the $.ajax method to make an AJAX request.

Lets back to the point where we have started, we want to re-write our previous example with the putting $ symbol in action.

   $('p');
The above code will select all the values that are inside the ‘p’ element. But what if you want to select only the ‘p’ element who has a matching id of ‘myElement’ or lets say who has matching class name of ‘something’. How would you select them?
Before answering this question lets write down the basic generic syntax for selecting a DOM element.
Basic selection syntax : $(‘selector’
One thing I would like to point  you is that instead of single apostrophe(‘   ‘) you could happily use double quotes ( ” “) and your code will run without causing any break. I Prefer single apostrophe(‘   ‘) for javascript and its framework and I will use this throughout my tutorial.
#id Selection: To select a particular id pass it to the jQuery function or $(‘ ‘) function with # symbol before the id name.
id Selection Syntax : $(‘#selector’)

HTML:

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is a another paragraph.<p>
<p id="myID">This is a paragraph.</p>
<p id="foo.bar">This is a paragraph.</p>
</body>

jQuery:

     $('#myID');
     $('#foo\\.bar');
 To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. In the above example, an element with id="foo.bar" was selected with  $("#foo\\.bar").
So far we have seen the basic building block of selecting an element from DOM. But what if the jQuery code runs before the DOM is ready? Shall our jQuery code smart enough to wait till the DOM is fully loaded?

Well, literally if we say, the answer is NO.
That means we are in need of some kind of mechanism that would ensure that our scripts/code will run once the DOM is fully loaded, not necessarily the contents(image, video etc). This actually ensures that any elements being accessed are actually in existence, so the script won’t return any errors. Other then this it also ensures that your code is unobtrusive i.e. it’s separated from content (HTML) and presentation(CSS). One way to achieve this is to call the jQuery ready() function and pass your function as parameter.
$(document).ready(function(){
   // Your jQuery code goes here
});

We could use the short hand form to perform the same task.

$(function(){
   // Your jQuery code goes here
});

You can use any of the above syntax, both are perfectly fine, its just depend on your matter of comfort zone. But remember the full form document ready is much easier to understand/grasp for those who are new in jQuery. So, if you are about to write code which other might see then the extended/full form is preferable.

function DoSomethingMeaningful()
{
   alert("Just an alert!");
}
$(DoSomethingMeaningful);

If you are not comfortable with the ready() event there has another way you could ensure that your code will run once the DOM is ready. Simply write down your jQuery script in an HTML document before the closing element. As all the browser parse the document from top to bottom so putting your code before the closing element ensures that your DOM is completely loaded.

If you are using multiple JavaScript library on your page, chances are that <code>$</code> might be already in use by another library, which can cause jQuery not to work. On such scenario it is advisable that you use jQuery.noConflict before loading the other libraries.

.class Selection: To select a particular class pass it to the jQuery function or $(‘ ‘) function with . symbol before the class name.

Class Selection Syntax : $(‘.selector’)

Lets select the ‘p’ element who has a matching class “test”.

HTML:
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p class="test">This is a paragraph.</p>
</body>

jQuery:

     $('.test');

So far you have learn how to select a particular element in DOM, I rather should say you have actually learn how to point a particular element in DOM. Just by pointing the element you now have the object that represents your element 🙂

HTML:

<body>
<h2>This is a heading</h2>
<p class="test">This is a paragraph.</p>
</p>

jQuery:

     var whatIHave= $('.test');
     alert(whatIHave);

You could use this object for further processing. Lets say want to retrieve the inner text for the selected element. We could get that by calling text() function on that particular object.
jQuery:

     var myElement= $('.test');
     alert(myElement.text());

Similarly, if you want your variable to hold all HTML (including text) of your desired element then instead of calling text() function you should html() function.
jQuery:

     var myElement= $('.test').html();

We definitely made a good progress in learning the nitty-gritty concept but we have not done anything meaningful yet except showing the selected element’s text in an alert box, in the next section we will try to DO SOMETHING meaningful with the element that we have selected in the last section. Once we learn how to DO SOMETHING with the DOM element we will come back and have a look on the other selectors that ships with jQuery.

2. Do Something: In this section we will change the contents of the selected element. First start with changing the text property of a selected element.

jQuery:

     var myElement= $('.test').text('This is the new content.');
     //We have replaced the existing content

Now what if we want to append our text just after the existing content. We could do that easily by calling the append() function and pass the desired text as parameter.

jQuery:

     var myElement= $('.test').append(<p>I am new Content.</p>);
     //add the new content at the end

We could easily change the entire html syntax.

jQuery:

     var myElement= $('.test').html(<h2>I am new Content. </h2>);
     //content inside .test will be replaced with that specified

jQuery also offer syntax like appendTo(), prepend(), prependTo(), before(), insertBefore(), after(), insertAfter(), which work similarly to append but with their own unique characteristics. Few of this syntax will be covered in “Extended Concept: CREATE SOMETHING” section.

As you probably have noticed the entire lesson is build on each other, the whole lesson has connectivity with each other. The example, the code sample that I have presented so far might be found little bit slow somewhere but those are the key concepts that should have in your back.
At this point we are good enough to narrow down the basic syntax for our Simple Concept i.e. Find Something Then Do Something.

Simple concept syntax : $(selector).action()

  • $ sign to define/access jQuery
  • A (selector) to point the desired HTML elements
  • The jQuery action() that has to be performed on the element(s)

Since we are now enriched with the SIMPLE CONCEPT syntax let write some more jQuery code to increase our comfort zone.

Lets start by hiding all the ‘p’ elements. We will use the hide() function for this purpose.

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is a another paragraph.<p>
<p id="myID">This is a paragraph.</p>
</body>

jQuery:

  $(document).ready(function(){
     $('p').hide();
     });
  });

In the above example we have not specified any parameter for the hide() function, but we certainly could provide additional information for more control on our hide() function.

The hide() function accepts two optional parameter.

  • The first optional parameter specifies the speed of the hiding of an element. Possible values could be “slow”, “fast”, or milliseconds.
  $(document).ready(function(){
     $('p').hide("fast"); //don't forget the double quotes!
     $('h1').hide(1000); //this is in millisecond!
     });
  });
  • The second optional parameter is a callback function to be executed after the hide() completes
  $(document).ready(function(){
     $('h1').hide(1500, function(){alert("I will pop up after the element gets hide")});
     });
  });

The exact opposite of hide() function is show() function. It also has the exact same optional parameter. Use of show() function is a free time assignment for you.

Advertisements