Jquery Basics

Let  us see how to use jQuery in your page

For the viewers convenience  I have divided this tutorial into several parts.

Before entering into the concepts lets see What is Jquery?

jQuery is a JavaScript framework, which purpose is to make it much easier to use JavaScript on your website. You could also describe jQuery as an abstraction layer, since it takes a lot of the functionality that you would have to write many lines of JavaScript to accomplish and wraps it into functions that you can call with a single line of code. It’s important to note that jQuery does not replace JavaScript, and while it does offer some syntactical shortcuts, the code you write when you use jQuery is still JavaScript code.

With that in mind, you should be aware that you don’t need to be a JavaScript expert to use jQuery. In fact, jQuery tries to simplify a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation, so that you may do these things without knowing a lot about JavaScript.

There are a bunch of other JavaScript frameworks out there, but as of right now, jQuery seems to be the most popular and also the most extendable, proved by the fact that you can find jQuery plugins for almost any task out there. The power, the wide range of plugins and the beautiful syntax is what makes jQuery such a great framework. Keep reading to know much more about it and to see why we recommend it.

BASE-I

To use jQuery, you need to include it on the pages where you wish to take advantage of it.   You can do this by downloading jQuery from their website at  www.jquery.com.   There is usually a choice between a “Production” version and a “Development” version. The first is for your live website, because it has been minified and compressed to take up the least amount of space, which is important for your visitors, whose browser will have to download the jQuery file along with the rest of your website. For testing and development, the “Development” version is best. It hasn’t been minified or compressed, so when you run into an error, you can actually see where in jQuery it happens.

Once downloaded, you will have to reference the jQuery JavaScript file on your pages, using the <script> HTML tag. The easiest way is to place the downloaded jquery.js file in the same directory as the page from where you wish to use it and then reference it like this, in the section of your document:

<script type="text/javascript" src="jquery-1.5.1.js"></script>

A part of your page should now look something like this

<head>
      <title>jQuery test</title> 
        <script type="text/javascript" src="jquery-1.5.1.js"></script> 
</head>

A more modern approach, instead of downloading and hosting jQuery yourself, is to include it from a CDN (Content Delivery Network). Both Google and Microsoft host several different versions of jQuery and other JavaScript frameworks. It saves you from having to download and store the jQuery framework, but it has a much bigger advantage: Because the file comes from a common URL that other websites may use as well, chances are that when people reaches your website and their browser requests the jQuery framework, it may already be in the cache, because another website is using the exact same version and file. Besides that, most 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 the US and so on.

You can use jQuery from a CDN just like you would do with the downloaded version, only the URL changes. For instance, to include jQuery 1.5.1 from Google, you would write the following:

I suggest that you use this approach, unless you have a specific reason for hosting jQuery yourself.

BASE-II

Simple Hello World program

Every decent programming tutorial will start with a “Hello, world!” example and this tutorial is yet another one of them. In the previous chapter, we learned how to include jQuery on our page, so that we may start using all of its great features. You need to know a bit more about how jQuery works, before you can start writing your own code, but just to make sure that everything is working, and for you to see how simple jQuery is, let’s kick off with a little example:

<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>

Okay, so we have a div tag with the id of “divTest1”. In the JavaScript code we use the $ shortcut to access jQuery, then we select all elements with an id of “divTest1” (there is just one though) and set its text to “Hello, world!”. You may not know enough about jQuery to understand why and how this works, but as you progress through this tutorial, all of the elements will be explained in detail.

Even such a simple task as this one would actually require quite a few extra keystrokes if you had to do it in plain JavaScript, with no help from jQuery:

<div id="divTest2"></div>
<script type="text/javascript">
document.getElementById("divTest2").innerHTML = "Hello, world!";
</script>

And it would be even longer if our HTML element didn’t have an ID, but for instance just a class.

Normally though, you wait for the document to enter the READY state before you start manipulating its content. The above examples will work in most browsers and likely even work when you do more advanced stuff, but certain tasks may fail if you try to do them before the document is loaded and ready

BASE-III

[ Concepts about The ready event]

As mentioned in the previous chapter, it’s good practice to wait for the document to be fully loaded and ready, before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section, either directly or through a link to an external JavaScript file. You may do just that by placing your code inside the document ready event. We will use the same example as in the “Hello, world!” chapter, but this time the code is inside the ready event:

<div id="divTest1"></div>
<script type="text/javascript">
function DocumentReady()
{
        $("#divTest1").text("Hello, world!");   
}

$(document).ready(DocumentReady);
</script>

What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.

However, we can shorten this a bit by using an anonymous function of JavaScript instead. This basically just means that instead of declaring the function and giving it a name, we simply create it and then immediately passes the reference to the ready() function. If you’re new to JavaScript, then this might seem overly complicated, but as you get used to it, you might appreciate the fewer keystrokes and the less space needed to accomplish the same:

<div id="divTest2"></div>
<script type="text/javascript">
$(document).ready(function()
{
        $("#divTest2").text("Hello, world!");   
});
</script>

But of course, this wasn’t even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:

<div id="divTest3"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest3").text("Hello, world!");   
});
</script>

In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won’t even realize it.

As already described, wrapping your code in the ready event function is best practice for working with jQuery in your document, and therefore you will see this tutorial using the approach in most of the examples, unless skipped to keep example sizes down.

BASE-IV

[ Concepts about Method chaining]

Yet another one of the really cool aspects of jQuery is the fact that most of the methods returns a jQuery object that you can then use to call another method. This allows you to do command chaining, where you can perform multiple methods on the same set of elements, which is really neat because it saves you and the browser from having to find the same elements more than once. Here’s an example, and don’t worry about the jQuery methods used in the following examples – they will be explained in later chapters:

<div id="divTest1"></div>
<script type="text/javascript">
        $("#divTest1").text("Hello, world!").css("color", "blue");
</script>

It works like this: We instantiate a new jQuery object and select the divTest1 element with the $ character, which is a shortcut for the jQuery class. In return, we get a jQuery object, allowing us to manipulate the selected element. We use that object to call the text() method, which sets the text of the selected element(s). This method returns the jQuery object again, allowing us to use another method call directly on the return value, which is the css() method.

We can add more method calls if needed, but at some point, the line of code will become quite long. Fortunately for us, JavaScript is not very strict when it comes to the syntax, so you can actually format it like you want, including linebreaks and indentations. For instance, this will work just fine as well:

<div id="divTest2"></div>
<script type="text/javascript">
        $("#divTest2").text("Hello, world!")
                                        .removeClass("blue")
                                        .addClass("bold")
                                        .css("color", "blue");                                  
</script>

JavaScript will simply throw away the extra whitespace when interpreting the code and execute it as one long line of code with several method calls.

Note that some methods doesn’t return the jQuery object, while others only return it depending on the parameters you pass to it. A good example of that is the text() method used above. If no parameters are passed to it, the current text of the selected element(s) is returned instead of a jQuery object, while a single parameter causes jQuery to set the specified text and return a jQuery object.

BASE-V

Lets see about Selectors 

A very common task when using JavaScript is to read and modify the content of the page. To do this, you need to find the element(s) that you wish to change, and this is where selector support in jQuery will help you out. With normal JavaScript, finding elements can be extremely cumbersome, unless you need to find a single element which has a value specified in the ID attribute. jQuery can help you find elements based on their ID, classes, types, attributes, values of attributes and much, much more. It’s based on CSS selectors and as you will see after going through this tutorial, it is extremely powerful.

Because this is such a common task, the jQuery constructor comes in several forms that takes a selector query as an argument, allowing you to locate element(s) with a very limited amount of code for optimal efficiency. You can instantiate the jQuery object simply by writing jQuery() or even shorter using the jQuery shortcut name: $(). Therefore, selecting a set of elements is as simple as this:

$(<query here>)

With the jQuery object returned, you can then start using and altering the element(s) you have matched. In the following chapters, you will see examples of some of the many ways you can select elements with jQuery.

[Using ID’s and Classes]

The #id selector

A very common selector type is the ID based, which we saw in the “Hello, world” example. It uses the ID attribute of a HTML tag to locate the desired element. An ID should be unique, so you should only use this selector when you wish to locate a single, unique element. To locate an element with a specific ID, write a hash character, followed by the ID of the element you wish to locate, like this:

$("#divTest")

An example of it in use:

<div id="divTest"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest").text("Test");
});
</script>

Now, while there is only a single element that matches our query above, you should be aware that the result is a list, meaning that it can contain more than one element, if the query matches more than one. A common example of this is to match all elements which uses one or several CSS classes.

The .class selector

Elements with a specific class can be matched by writing a . character followed by the name of the class. Here is an example:

<ul>
        <li class="bold">Test 1</li>
        <li>Test 2</li>
        <li class="bold">Test 3</li>
</ul>
<script type="text/javascript">
$(function()
{
        $(".bold").css("font-weight", "bold");
});
</script>

The element selector

You can also match elements based on their tag names. For instance, you can match all links on a page like this:

$(“a”)

Or all div tags like this:

$(“div”)

If you use a multi-element selector, like the class selector we used in the previous example, and we know that we’re looking for elements of a specific type, it’s good practice to specify the element type before the selector. Not only is it more precise, it’s also faster for jQuery to process, resulting in more responsive sites. Here is a re-written version of the previous example, where we use this method:

$("span.bold").css("font-weight", "bold");

This will match all span elements with “bold” as the class. Of course, it can be used with ID’s and pretty much all of the other selectors as well.

Selectors can do much more for you though. Read on for more cool exam

BASE-VI

[Using Attributes]

In the previous chapter, we saw how we could find elements in a page from their class or their ID. These two properties are related because of the fact that you can use them to style the elements with CSS, but with jQuery, you can actually find elements based on any kind of attribute. It comes with a bunch of attribute selector types and in this article, we will look into some of them.

Find elements with a specific attribute

The most basic task when selecting elements based on attributes is to find all the elements which has a specific attribute. Be aware that the next example doesn’t require the attribute to have a specific value, in fact, it doesn’t even require it to have a value. The syntax for this selector is a set of square brackets with the name of the desired attribute inside it, for instance [name] or [href]. Here is an example:

<span title="Title 1">Test 1</span><br />
<span>Test 2</span><br />
<span title="Title 3">Test 3</span><br />

<script type="text/javascript">
$(function()
{
        $("[title]").css("text-decoration", "underline");
});
</script>

We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value.

Find elements with a specific value for a specific attribute

Here’s an example where we find elements with a specific value:

<a href="http://www.google.com" target="_blank">Link 1</a><br />
<a href="http://www.google.com" target="_self">Link 2</a><br />
<a href="http://www.google.com" target="_blank">Link 3</a><br />

<script type="text/javascript">
$(function()
{
        $("a[target='_blank']").append(" [new window]");
});
</script>

The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value “_blank” and then append the text “[new window]” to them. But what if you’re looking for all elements which don’t have the value? Inverting the selector is very easy:

$("a[target!='_blank']").append(" [same window]");

The difference is the != instead of =, a common way of negating an operator within many programming languages.

And there’s even more possibilities:

Find elements with a value which starts with a specific string using the ^= operator:

$("input[name^='txt']").css("color", "blue");

Find elements with a value which ends with a specific string using the $= operator:

$("input[name$='letter']").css("color", "red");

Find elements with a value which contains a specific word:

$("input[name*='txt']").css("color", "blue");

BASE-VII

[Using Parent/child relation selectors]

jQuery also allows you to select elements based on their parent element. There are two variations: One which will only match elements which are a direct child to the parent element, and one which will match all the way down through the hierarchy, e.g. a child of a child of a child of a parent element.

The syntax for finding children which are direct descendants of an element looks like this:

$(“div > a”)

This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:

$(“div a”)

Here’s an example where we color bold tags blue if they are directly descending from the first test area:

<div id="divTestArea1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTestArea2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>

<script type="text/javascript">
$("#divTestArea1 > b").css("color", "blue");
</script>

As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or “grand children” as they are sometimes called:

<div id="divTestArea1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTestArea2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>

<script type="text/javascript">
$("#divTestArea1 b").css("color", "blue");
</script>

Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We’ll look into that in another chapter of this tutorial.

BASE-VIII

Fading Effects

Doing simple animation is very easy with jQuery. One of the effects it supports out-of-the-box, is fading an element in and out of visibility. Here’s a simple example, where we fade in an otherwise hidden box, using the fadeIn() method:

<div id="divTestArea1" style="padding: 50px; background-color: #89BC38; text-align: center; display: none;">
        <b>Hello, world!</b>
</div>
<a href="javascript:void(0);" onclick="ShowBox();">Show box</a>
<script type="text/javascript">
function ShowBox()
{
        $("#divTestArea1").fadeIn();
}
</script>

You can fade a lot of different elements, like divs, spans or links. The fadeIn() method can take up to three parameters. The first one allows you to specify the duration of the effect in milliseconds, or “fast” or “slow”, which is the same as specifying either 200 or 600 milliseconds. Here’s an example of it in use:

<div id="divTestArea21" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div>
<div id="divTestArea22" style="width: 50px; height: 50px; display: none; background-color: #C3D1DF;"></div>
<div id="divTestArea23" style="width: 50px; height: 50px; display: none; background-color: #9966FF;"></div>
<a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a>
<script type="text/javascript">
function ShowBoxes()
{
        $("#divTestArea21").fadeIn("fast");
        $("#divTestArea22").fadeIn("slow");
        $("#divTestArea23").fadeIn(2000);
}
</script>

Don’t mind all the HTML, it’s just there so that you can see the difference between the fading durations. Now, the second parameter can either be the name of an easing function (which we won’t use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here’s an example of that, combined with the use of the fadeOut() method, which obviously has the reverse effect of fadeIn():

<div id="divTestArea3" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea3").fadeIn(2000, function()
        {
                $("#divTestArea3").fadeOut(3000);
        });
});
</script>

There may be situations where you want to fade an element in our out depending on its current state. You could of course check if it is visible or not and then call either fadeIn() or fadeOut(), but the nice jQuery developers have supplied us with a specific method for toggling an element, called fadeToggle(). It takes the same parameters as fadeIn() and fadeOut(), so it’s very easy to use. Here’s a little example:

<div id="divTestArea4" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><br />
<a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a>
<script type="text/javascript">
function ToggleBox()
{
        $("#divTestArea4").fadeToggle("slow");  
}
</script>

And that’s how easy it is to use the fading effects of jQuery.

BASE-IX

Sliding elements

In the previous chapter, we saw how we could fade elements in and out of visibility using the fading methods of jQuery. However, sometimes a sliding effect is a better choice, and for that, jQuery has a set of matching methods for doing just that. Let’s kick off with a simple example of it, where we use the slideDown() method:

<div id="divTestArea1" style="padding: 50px; background-color: #89BC38; text-align: center; display: none;">
        <b>Hello, world!</b>
</div>
<a href="javascript:void(0);" onclick="ShowBox();">Show box</a>
<script type="text/javascript">
function ShowBox()
{
        $("#divTestArea1").slideDown();
}
</script>

For hiding the box again, we can use the slideUp() method. They both take the same set of parameters, which are all optional. The first parameter allows you to specify a duration for the effect in milliseconds, or “fast” or “slow”, which is the same as specifying either 200 or 600 milliseconds.Let’s try an example where we do just that:

<div id="divTestArea21" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div>
<div id="divTestArea22" style="width: 50px; height: 50px; display: none; background-color: #C3D1DF;"></div>
<div id="divTestArea23" style="width: 50px; height: 50px; display: none; background-color: #9966FF;"></div>
<a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a>
<script type="text/javascript">
function ShowBoxes()
{
        $("#divTestArea21").slideDown("fast");
        $("#divTestArea22").slideDown("slow");
        $("#divTestArea23").slideDown(2000);
}
</script>

There’s a bit more HTML than usual, but that’s only there for you to be able to see the different paces in which the boxes are shown. Notice how the first box is there almost instantly, the second box is pretty close and the third box is slower, because it uses a full two seconds to slide down.

Now, the second parameter can either be the name of an easing function (which we won’t use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here’s an example of that, combined with the use of the slideUp() method:

<div id="divTestArea3" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea3").slideDown(2000, function()
        {
                $("#divTestArea3").slideUp(3000);
        });
});
</script>

The ability to do this can be very useful for combining several effects, as you can see. In this example, the callback function we supply will be called as soon as the slideDown() method is completely finished and then the slideUp() method is called.

In case you want to simply slide an element up or down depending on its current state, the jQuery developers have provided us with a nice slideToggle() method for doing just that. Check out the next example, where we use it:

<div id="divTestArea4" style="width: 50px; height: 50px; display: none; background-color: #89BC38;"></div><br />
<a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a>
<script type="text/javascript">
function ToggleBox()
{
        $("#divTestArea4").slideToggle("slow"); 
}
</script>

BASE-X

Custom animations with the animate() method

In previous chapters, we looked into the built-in fading and sliding effect methods of jQuery. However, you can much more than just that. With the animate() method, you can create custom animations where you manipulate pretty much any numerical CSS property of an element. This allows you to e.g. move a box slowly across the screen or have it jump up and down. Let’s try something very simple:

<div style="height: 60px;">
        <div id="divTestBox1" style="height: 50px; width: 50px; background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox1").animate(
                {
                        "left" : "200px"
                }
        );
});
</script>

The first, and only required, parameter of the animate function is a map of the CSS properties that you wish to have altered. In this case, we have an absolutely positioned div element, which we tell jQuery to move until it has reached a left property of 200 pixels.
The second parameter allows you to specify the duration of the animation in milliseconds or as “slow” or “fast” which is the same as 600 or 200 ms. With this, we can slow down the above example as much as we want:

<div style="height: 60px;">
        <div id="divTestBox2" style="height: 50px; width: 50px; background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox2").animate(
                {
                        "left" : "200px"
                }, 
                5000
        );
});
</script>

As the third parameter, we can specify a callback function to be called once the animation is done. This can be very useful for performing a number of different animations in a row. For instance, check out this example:

<div style="height: 40px;">
        <div id="divTestBox3" style="height: 20px; width: 20px; background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox3").animate(
                { "left" : "100px" }, 
                1000,
                function()
                {
                        $(this).animate(
                                { "left" : "20px" },
                                500,
                                function()
                                {
                                        $(this).animate({ "left" : "50px" }, 500);
                                }
                        )
                }
        );
});
</script>

It might seem a bit overwhelming, but what we do is that we call the animate method and ask for the left property of our test “div” to be animated until it reaches a left of 100 pixels. We want it to take 1 second (1000 milliseconds) and once it completes, we wish for a new animation to start, which moves it back to 20 pixels within half a second, and as soon as THAT animation is done, we move it a bit right again, so that it now has a left property of 50 pixels.

However, since jQuery comes with queue functionality for animations, you can actually achieve the above example in a much simpler manner. This however only applies when you want a set of animations to performed after each other – if you want to do something else when an animation is complete, the above example will still be the way to go. Here’s the queue version:

<div style="height: 40px;">
        <div id="divTestBox4" style="height: 20px; width: 20px; background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox4").animate({ "left" : "100px" }, 1000);
        $("#divTestBox4").animate({ "left" : "20px" }, 500);
        $("#divTestBox4").animate({ "left" : "50px" }, 500);
});
</script>

Reference Site

Advertisements

4 thoughts on “Jquery Basics

  1. Pingback: Questions About Jquery Css | Top Apprentice Blog

  2. Pingback: Questions About Jquery Css | Top Apprentice Blog

  3. Pingback: Top Apprentice Blog Questions About Jquery | Top Apprentice Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s