by ivan at 2013-08-04
jQuery is javascript library that provides a cross-browsing solution for manage and modify the DOM easily. But we aren't here for presentations. We like to develop. Ok, don't worry. Here we go!
In this article we don't like to explain all the features of jQuery. For this, we have the official site, that is very complete and very useful when we are developing. The reason of this article, like all of the Start with... section is show which are the basics that we need to know for start to use this technology.
As we said, jQuery is a javascript libary. For this, we need to include it in our HTML. There are two different forms to do this:
Show me the money! Don't worry, I'm joking. jQuery have an alias,
$
, than can be used for no put jQuery
every time. For this, every time that we need to use some function of jQuery,
we can use $
in place of jQuery
.
However, there are more javascript libraries that uses $
as an alias, like MooTools. For this reason, if you need to play with more of one
of this libraries, jQuery provides the jQuery.noConflict()
method, that disallow the $
alias for the jQuery library.
When we use jQuery is better to ensure that all the DOM is ready. Why? jQuery works a lot with the DOM and if isn't ready when we start to execute our scripts, is possible that we don't get the result that we hope. For this, we can do this and ensure that our code doesn't have more problems than our bugs:
]]>
However, sometimes happens that we can't put all the code in the same place.
Don't worry, we can't put all the $(document).ready()
statements that we need. Isn't the best solution in terms of performance but...works.
One more thing. The stuff that we define in this statements are invisible outside the
statement. This means that if we define a function inside a
$(document).ready()
only can be called
inside this statement. The same happens with the varibles.
For this reason is a good idea create javascript classes and define
the functions outside the statements, because the functions aren't called
automatically (not for the moment) and we can ensure that only are called
inside our $(document).ready()
statements
(For ensure that we don't have problems for the DOM, do you remember?).
If something is important when we talk about jQuery is the selector feature.
If we need to define it, I think that the best form for do it is using the
CSS language as an example. When in CSS we write #element-id
we are thinking in set the styles of the element with
id = 'element-id'
, right? Ok,
in jQuery is the same, but more powerfull.
Below, some examples:
$('h1')
=> Select all the h1 elements in the document.
$('#my-id')
=> Select all the elements with and my-id
id property.
$('.my-class')
=> Select all the elements with the class my-class
$('a[href="http://butler.ivgam.com/"]')
=> Select all the a elements with an href property with value "http://butler.ivgam.com/"
$('a[href^="http:"]')
=> Select all the a elements with an href property that starts with "http:"
$('a[href$=".com/"]')
=> Select all the a elements with an href property that ends with ".com"
$('a[href*="butler"]')
=> Select all the a elements with an href property that contains in any place "butler"
$('ul li:nth-child(2)')
=> Select all the li tags that are the second child of their parent's ul tag.
$('input:checked')
=> Select all the inputs that are checked
All this selectors can be combined ones with the others to create an extreme flexible solution for access to anyplace in the DOM. Is only practise, try and error.
$(this)
is possible one of the most
writted things when we use jQuery. This selector is an autodefined
element that contains the element that have the jQuery focus
in every moment.
For be more clear, we explain it with an example:
In the first console.log($(this))
, we
print the $(document)
element, but
in the second one, the current position of the
my-array
array in every iteration
of the each loop.
If we are inside the function of an event, $(this)
contains the element that triggers this event.
We have two forms to do loops in jQuery. The first one
is $.each()
, that have the next
sintax:
And $('li').each()
, that is very
similar, but isn't the same.
If the selectors are important, the AJAX feature too. Why? Before jQuery, create an asynchronous javascript execution needs and if/else statement for check in which type of browser we are. With jQuery, the browser is transparent for us, and we can focus all our efforts in develop our solution.
Create an AJAX request in jQuery is very easy and can be do it with
more than one function, but all extends of $.ajax()
,
that is the most complete.
For this reason, for can do all with it, I prefer use every time
$.ajax()
and memorize their sintax. Isn't
difficult and is very useful.
Below, a basic example:
As you can view, the sintax isn't difficult. However, for reduce the complexity, I will explain the params that I used:
$.ajax()
also defines params for requests that finish in error or for complete requests) we will
execute the lines that are inside this function.
We need to understand that if the async
param is set to
true
the program doesn't wait for the
response and continue executing the javascript that have below
the $.ajax()
function. This means that
if in the success function we update a variable, this can have
the final result or the previous result when we use it in the
lines that are below the $.ajax()
statement. Be careful!
If you need more information or view all the params list of this function, you have the official documentation here.
Until now, we explain in every section only one function. However, we consider than this three functions needs to come together. Why? It's simple: Together are very powerful.
Well, what's parent()
,
what's children()
and
what's find()
? Are functions that
allows us to select specific nodes that are relationed
with the node that we select previosly.
parent()
access to the inmediate
parent node of the selection. For example, if we have a
li tag, $(this).parent()
returns
the ul tag. This function have a variant that is called
parents()
, that returns all
the parents that have our current node.
children()
is the opposite. With
it, we obtain the nodes that are defined inside the
current selection.
And find()
provides a form to use
again the jQuery selectors for filter the childrens that
have the current selection. What? I think that the best for
understand it is with an example.
If we have the last HTML structure and we do
$('#my-ul').find('img.active')
, we
obtain the first image. In this example, we can do
$('#my-ul img.active')
too, but sometimes
the selector isn't very easy and is more comprenhensible
use the find()
. Also, sometimes
you have a previous element save in a variable and
find()
is a good form to start
again to play with the selectors and find the next element
that we need.
Sometimes we need to add content or modifiy
the existing one in our DOM. For this, jQuery provides
lots of methods, but we select three that we think
that are the most useful:
append()
,
prepend()
,
html()
.
This three methods receives a String as a parameter. The first
one append()
, put this chain
of characters as the last child of our selection. The second one,
prepend()
, as the first child of
our selection and...the last one html()
,
replaces the content of our selection with string that
we put as a parameter.
Below, more visual:
Example of prepend()
Example of append()
Example of html()
If we have methods for add or change content, obviously, we
have also methos for remove content. Principally, there are two
methods: remove()
and
empty()
. The first one deletes elements
that are in the selection and the second one, deleted only
the html that are inside, but no the tag that we select.
The last two sections talk about add or remove general content, but sometimes, we only need to change specific things, like a tag attribute or if one checkbox is checked or not.
For this reason, jQuery provides lots of methods for do this specific tasks. However, we think that with the next five, is sufficient for the major part of the tasks.
attr()
:prop()
:css()
:Well, we arrive to the last section of this article. Until here, all is very simple, right? I think that this section have the same complexity but is possible that is more interest for our readers. Why? I don't know, but when all the people starts with jQuery, starts doing a click function or a hover effect. We are humans, we like to interact with the things. If not...is very boring.
Why events? Ok, it's true that standard HTML provides a way to manage some events putting attributes in their tags, but is very hard to put the things pretty when we have injected javascript inside the tags. Is hard and isn't scalable because if the same code need to be executed in more than one click event, we need to copy and paste the same code one time and another for all our code. Bad, hard and ugly.
For this reason, for be clean, pretty and scalable, jQuery provides some functions that allow us to manage all the events that success in our application. There are lots of ways to do the same. For this, we center our focus in the standard one. Why? Is the same reason that in the $.ajax() section. If we know the standard one, we can do it all. If we know the specific ones, it's possible that we don't know which is the form for do it all.
Said this, we start. The standard form to set and event is
with the method .on()
. This method have
two types of calls, with two parameters and with three parameters.
Normally, we use the two parameters sintax with one exception
that I will explain after.
Two parameters example
As you can view, the sintax is very simple. We write our selector, we call to the .on() function and...what's 'event'? 'event' is our event/s type/s. In this string we can put, separated by white spaces all the events that we need to catch for this selector. The most common events are 'click', 'hover', 'keyDown', 'keyUp', 'change'...lots, there are lots. There are lots and we can also define our custom events. When are triggered the custom events? This is a start article and this a question for the next level, but if you are curious, you can vie how trigger and event here.
Ok, we have our event setted and now we only need to wait that our users trigger this event with a click of with a hover or with the event type that we define. Perfect, this is true, but we need to know a very important thing: When we set an event, this event only affect to the elements that check the selector in this DOM moment.
This means that if we create new elements, this aren't inside the event rule. And...Which is the form for create a 'global' event that operates with all the elements for the ages? Well, we said before that there are a three parameters call, right? One of the uses is for create 'global' events. This is the sintax:
As you view, isn't more difficult. However, the perfomance of this solution isn't the best in the world. For this, use it only in the cases that is imprescindible. If you define all your events as global events, jQuery needs to manage every time there are new elements and we are sure that you don't like to burn your visitors machines, right? (remember that javascript is a client-side language and their execution depends of the user machine, that sometimes is worst that we hope).
And even here the Start with... of today. If you have more questions, if you think that we doesn't explain a feature that you consider that is basic or if you like to say thank you, you can send us an email or post your comments below.
Thanks a lot. See you at the next!