MorkaLork Development

Interesting stuff I've picked up over the years...

Using jQuery

2009-12-21 09:32:59 | 270 views | jquery javascript basics

What is jQuery?


Well, the jquery homepage, jquery.com does have the best definition, so you ought to go there first. In short, it's a javascript framework that makes working with javascript easier.

The main reasons to use jquery are:

It has selectors. This means you can bind a function to a html or css element/class/id which means that it will run at any given time that the conditions are true.

Example: $('#myDiv').click(function());

The above code will run every time someone clicks on the div with the id 'myDiv'.


jQuery also make browser compatibility issues a bad memory, nothing more. The main reason why I've always hated javascript(oh yes!) is the fact that most browsers handle javascript differently from Internet Explorer. This often leads to stupid if-statements such as the following one (taken from w3c's PHP/AJAX tutorial):

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}


The fact that jQuery makes this go away is enough to use the framework.


Talking about Ajax, that is another reason why you should use jQuery, there are several jQuery plugins that makes working with Ajax very easy and fun. I will however write a separate article about how to use jQuery with Ajax.

More reasons? An enormous amount of plugins to use. A documentation that is incredibly well written. A very tiny framework (55.9 kb at this date, using the minimized version). There are more reasons, but this will have to do.


How to use it?


jQuery has an event called 'ready' which makes sure that the page DOM(Document Object Model) has been properly loaded since jQuery relies heavily on the DOM. Everything you do should be placed inside the 'ready' event.

In this first jQuery article I will assume that you have read the getting started with jquery tutorial on jquery.com since it is a fantastic guide on how to get started. I will start of slow and raise the pace as we go along.

First, selectors


Knowing how to select elements using jQuery is vital. jQuery is used with the dollar sign followed by a selector within a parenthesis:
$(x)

Here is a couple of examples:

$('#foo')Select all elements with id='foo'
$('div#foo')Select all div elements with id='foo'
$('div#foo p')Select all paragraphs within a div with id='foo'
$('p')Select all paragraphs
$('p:first')Select the first paragraph
$('.foo')Select all elements with class='foo'
$('input[type=text]')Select all input elements with type text


When you have selected an element you can make use of the 'this' keyword to access the current DOM object you are dealing with. For more information about 'this', visit this link.
So, the following short example will display how we bind an event to all paragraphs within a div with id myDiv (notice how we don't care what class the p has):

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#myDiv p').click(function(){
alert($(this).text());
});
});
</script>
</head>

<body>
<div id="myDiv">
<p>A paragraph</p>
<p class="myParagraph">A paragraph with a class</p>
<p>Just another paragraph</p>
</div>
</body>
</html>


We then use 'this' do select the current DOM object(which is the paragraph we clicked) and select its text property.


A basic use of jQuery


We will start of lightly by make a webpage that has one paragraph and one link. When pressing the link we will change the paragraph text to something else:

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#textChanger').click(function(){
$('#myParagraph').text("Goodbye world...");
});
});
</script>
</head>
<body>
<div id="myDiv">
<p id="myParagraph">Hello World!</p>
<a href="" id="textChanger">Change text</a>
</div>
</body>
</html>

View example here.

Notice how easy it is to follow the flow in the jQuery code. First we wait until the document has loaded the DOM. After that we set an event listener to the link. If someone presses the link we change the text of the element with id 'myParagraph'. It's very little code and still we have accomplished a lot.


Changing many elements at once


A good use of jQuery is to listen to classes. ID's should generally be used as unique identifiers where as many elements can share the same class. So we'll make three paragraphs that share the same css class, 'pClass', and add some css to these paragraphs. The css function let's us either get the a css property from an element or add one. We will make our paragraphs bold with a border in this example:

<html>
<head>
<!--Our css -->
<style type="text/css">
.pClass{ color: blue; }
</style>

<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#textChanger').click(function(){
$('.pClass').css({'font-weight':'bold', 'border':'1px #000 solid'});
});
});
</script>
</head>

<body>
<div id="myDiv">
<p class="pClass">Hello World!</p>
<p class="pClass">Hello Car!</p>
<p class="pClass">Hello Chair!</p>

<a href="" id="textChanger">Change text</a>
</div>
</body>
</html>


View example here.

What we do here is that we say 'change all elements that implements the pClass class and add boldness and a border'.


Using :first and :last filters


jQuery supports using filters on your selectors. This means that we can, as we did in the previous example, select all items and then filter out the ones we need. The :first and :last filters picks out(and this is a big surprise) the first and the last elements in the range of elements selected:

<html>
<head>
<!--Our css -->
<style type="text/css">
.pClass{ color: blue; }
</style>

<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#textChanger').click(function(){
$('.pClass:first').css({'font-weight':'bold', 'border':'1px #000 solid'});
$('.pClass:last').text('Hello Bird!');
});
});
</script>
</head>

<body>
<div id="myDiv">
<p class="pClass">Hello World!</p>
<p class="pClass">Hello Car!</p>
<p class="pClass">Hello Chair!</p>

<a href="" id="textChanger">Change text</a>
</div>
</body>
</html>


View example here.

What we do here is that we change the first p element that has the pClass class to bold text with a border. We also change the text of the last p element that implements the pClass.

This is actually so usefull that I'll show you another example using the :even and :odd filters:

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#textChanger').click(function(){
$('p:even').css({'color':'blue'});
$('p:odd').css({'color':'red'});
});
});
</script>
</head>

<body>
<div id="myDiv">
<p>Hello world</p>
<p>Hello world</p>
<p>Hello world</p>
<p>Hello world</p>

<a href="" id="textChanger">Change text</a>
</div>
</body>
</html>


View example here.

Here we change every even paragraph to blue text and every odd one to red. Remember though that jQuery bases this on a zero-index meaning that the first paragraph has index 0 and is as such an even paragraph.


jQuery and Looping


jQuery makes it very easy to loop through a collection of values. What's great is that looping through the DOM is even easier. This is a short example of how we can loop through all the paragraphs in the element with the 'myDiv' id:

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#textChanger').click(function(){
$('#myDiv p').each(function(i, item){
$(item).text("Paragraph " + i);
});
});
});
</script>
</head>

<body>
<div id="myDiv">
<p>Hello world</p>
<p>Hello world</p>
<p>Hello world</p>
<p>Hello world</p>

<a href="" id="textChanger">Change text</a>
</div>
</body>
</html>


View example here.

What we do here is that we use the $.each loop to traverse through all the paragraph items of the #myDiv element. We change the text in every paragraph using the indexer count.

This about does it for the basics of jQuery. I will write more articles that will be a bit more specific, but I hope you have enjoyed this one. If you are going to work with javascript, use jQuery!


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.