Showing posts with label Document Object Model. Show all posts
Showing posts with label Document Object Model. Show all posts

Friday, 25 November 2011

What is jQuery?

Since you've come to this page, you may already have a pretty good idea about what jQuery is, but to be on the safe side, here is a brief explanation. 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.

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.

Getting and setting content [text(), html() and val()]

The simplest aspect of DOM manipulation is retrieving and setting text, values and HTML. These three things might seem like the same thing, but they're not. Text is a textual (no HTML) representation of the inner content for all regular elements, values are for form elements and HTML is the same as text, but including any markup.

Fortunately for us, jQuery comes with a method for each of the three, allowing us to both retrieve and set these properties: The text(), html() and val() methods. Here's a little example which will show you the difference between them and how simple they are to use:

<div id="divTest">
        <b>Test</b>
        <input type="text" id="txtTest" name="txtTest" value="Input field" />
</div>

<script type="text/javascript">
$(function()
{
        alert("Text: " + $("#divTest").text());
        alert("HTML: " + $("#divTest").html());
        alert("Value: " + $("#divTest").val());

        alert("Text: " + $("#txtTest").text());
        alert("HTML: " + $("#txtTest").html());
        alert("Value: " + $("#txtTest").val());
});
</script>

So a call to one of these methods with no parameters will simply return the desired property. If we want to set the property instead, we simply specify an extra parameter. Here's a complete example:

<div id="divText"></div>
<div id="divHtml"></div>
<input type="text" id="txtTest" name="txtTest" value="Input field" />

<script type="text/javascript">
$(function()
{
        $("#divText").text("A dynamically set text");
        $("#divHtml").html("<b><i>A dynamically set HTML string</i></b>");
        $("#txtTest").val("A dynamically set value");
});
</script>

And that's how easy it is to set text, HTML and values.

These three functions comes with one overload more though, where you specify a callback function as the first and only parameter. This callback function will be called with two parameters by jQuery, the index of the current element in the list of elements selected, as well as the existing value, before it's replaced with a new value. You then return the string that you wish to use as the new value from the function. This overload works for both html(), text() and val(), but for the sake of simplicity, we only use the text() version in this example:

<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>

<script type="text/javascript">
$(function()
{
        $("p").text(function(index, oldText) {
                return "Existing text: " + oldText + ". New text:
A dynamically set text (#" + index + ")";
        });
});
</script>

We start out with three similar paragraph elements, which text is their only difference. In the jQuery code, we select all of them and then use the special version of the text() method to replace their current text with a newly constructed text, based on the two parameters that jQuery provides for us: The index of the current element as well as its current text. This new text is then returned to jQuery, which will replace the current text with the new one.