jQuery: Problems picking up the basics.
Hey all, it's been a while since my last blog post, sorry for that, been rather busy at work and at home at the same time, so haven't even had much time to even think about content for a post.
I've had to do a couple of small javascript bits for various pages latelty. My javascript is generally quite bad, but I've been looking at jQuery and have quite liked what you are able to do with it. Problem is, I've been struggling to find a decient page that helps me with the extreame basics of the javascript and jQuery, so I thought I'd try put something together. I have no idea whether or not this is going to be any good as I'm a noob when it comes to jQuery and javascript.
It took a bit of searching and multiple reads through the same section on the jQuery page, but here's the very basics of jquery.
function jqueryFunction() { $(document).ready(function () { alert('This only loads when the page is finished loading completely'); }); }
What the hell is going on here? Good question really. Lets try figure it out together, cause quite frankly it's still confusing me. Lets start off with the $ character/element.
The jQuery page says that $ is equal to alot of different things, those being the following:
I know right... a little confusing straight off the bat. Okay, so lets see if we can work out how this all goes together. Well first things first, $ is really only equal to one thing, that being jQuery(). The jQuery() is just used in 4 differnt ways. Suddenly, things are starting to seem a little but clearer arlready. Just by actually writing this out, I've suddenly understood it a little bit better.
Lets move on then and explore those 4 options a little and see how exactly they are used.
jQuery( expression, [context] )
What the jQuery has to say about it:
The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS), which then finds all matching elements.
By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context.
Okay, so this looks for CSS elements, if it can't find any, it looks for DOM elements (HTML elements).
$("div");
In the case above, it finds all the
<div> tags and returns them to be used (somehow, we'll get there eventually).
$("div", document.body);
This finds all the
<div> tags in the main document body and returns them to be used. I suppose this is exactly the same as the one above, so I would prefer to use this as it's clearer as to what is going on.
$("div", document.body.table);
This finds all the
<div> tags in all the tables and again returns them to us so we can use them.
$("div", document.body.table[0]);
This finds all the
<div> tags in only the first table.
Okay, so we're getting somewhere now. Lets have a look at the next implementation of jQuery() or $.
jQuery( html, [ownerDocument] )
What the jQuery has to say about it:
Simple elements without attributes, e.g., "<div/>", are created via document.createElement. All other cases are parsed by assigning the string to the .innerHTML property of a div element. The HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements.
All HTML must be well-formed, otherwise it may not work correctly across all browsers. This includes the case where $("<span>") may not work but $("<span/>") will (note the XML-style closing slash).
Okay, so how does this work then? Well, it creates HTML for you to inject into your page somehow.
$("<div><p>Hello</p></div>").appendTo("body")
So that should append that html to the end of our web page our web page. Lets test that quickly:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script> <script type="text/javascript"> $(document).ready(function() { alert("This alert will only pop up when the\npage has loaded, there should be\nno text."); $("<div><p>Hello</p></div>").appendTo("body"); }); </script> </head> <body> </body> </html>
So what this should do is, print a blank HTML page, the once the page has been fully rendered to the browser, you should get a pop up. The page will still be blank at this stage, because the alert/popup halts the code nicely for us. Once you click on okay, the word Hello should appear on the page. One could use this for a very degree of uses I suppose, like defining html for certain events and then injecting them into the page.
Lets move on to the next section.
jQuery( elements )
What the jQuery has to say about it:
This function accepts XML Documents and Window objects as valid arguments even though they are not DOM Elements. It will also accept another jQuery object, effectively returning $(other.get()).
To me, this effectively is the same as jQuery( expression, [context] ), but then as it was mentioned above, everything is based on jQuery( expression, [context] ), so it sorta makes sense.
Lets see how it works by adding some extra to our code from before and see how it works:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script> <script type="text/javascript"> $(document).ready(function() { alert("This alert will only pop up when the\npage has loaded, there should be\nno text."); $("<div><p>Hello</p></div>").appendTo("body"); alert("Lets change the text colour to green"); $(document.body).css('color', 'green'); alert("Lets hide all the divs now"); $(':div').hide(); }); </script> </head> <body> <div id='myDiv'>Some content in a div</div><p/> </body> </html>
In this case, the $(document.body) and $(':div') are our elements and as you can see they have a varied range of what they could actually be as it could be anything that is a DOM element.
*Edit* I missed this in the first post, but after a comment from marcorogers, I've added this section in and made a change above.
jQuery( callback )
What the jQuery has to say about it:
Allows you to bind a function to be executed when the DOM document has finished loading. This function behaves just like
$(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it.
You can have as many $(document).ready events on your page as you like.
So what this means in short (as macrogers said) is that the following bits of code do the same thing:
$(document).ready( function() { alert('The document is loaded'); } ) $(function() { alert('The document is loaded'); } );
If your wondering what a callback is, it is simply another method or function to call when the current evet/operation/function has finished running. In this case when the
ready() function (the one that checks to see if the document has finished loading) has returned, it will then execute the function you've defined as the call back function.
Where to from here...
Where to from here? Hello world of course. We can't just do a simply function that prints 'Hello World' to the screen (well we could, but we won't), we could do that with basic javascript, simply by doing an alert, so lets make it a little more complex. We'll create a div with some text in it and when the mouse hovers over the text, an alert will pop up with 'Hello World'. We'll then work from there.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script> <script type="text/javascript"> $(document).ready(function() { $('#hover').hover(function() { alert('Hello World!'); }); }); </script> </head> <body> <div id='hover'>Hover your mouse here</div> </body> </html>
As you can see, we gave our div an id, so this time around, we could specify which particular DOM element we wanted to play with. In the jquery script, we specify that by using the hash '#' in the jQuery selector ('$'); We then use the event 'hover', which says that when the mouse hovers this div, execute the specified call back function.
Lets change the jquery a little and get rid of the alert and rather manipulate the HTML within the div.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script> <script type="text/javascript"> $(document).ready(function() { $('#hover').hover(function() { $(this).html('Hello World'); }); }); </script> </head> <body> <div id='hover'>Hover your mouse here</div> </body> </html>
This is a much better example I think, cause now we really get a feel for some of the things we can do with jQuery. Here we again use the hover event, but this time, when we detect the event, we simple set the activated element's ($(this)) inner html with html( string ).
I feel I might need to point out at this stage. At no one point have we ever used a DOM attribute within the HTML to call the javascript. The events can all be managed within the jQuery, so there is little need to call it directly. This is not to say that you can't call jQuery from the HTML, you can, there's little need to do so though.
I'm going to stop there for now and we'll try pick this up again some other time as I'm personally wanting to learn from about jQuery and the things it can do for your web page. Hopefully I'll have the next installment to the Back to basics series of posts up soon, so keep an eye out for that too.
Tell next time, keep learning.
Syn
- synack's blog
- Login or register to post comments

Another interesting lesson here
Therefore the following three are equivalent. Funny that we never, ever see the first.
$(foo);function foo() {alert("loaded");};
$(function(){alert("loaded");});$(document).ready(function() {alert("loaded");});Lazy/Unreadable
I think mainly cause programers are lazy (I know I am) and like to fit stuff onto one line if they can, without making the code too unreadable. I personally don't see the second option much either, becuse it too is a little unreadble. If you don't know already know what you're looking at, it's hard to figure out.
$(document).ready();is more readable, specially to a person that doesn't know whats going on and it trying to do a quick debug.Hmmm. To be honest, I doubt
Hmmm. To be honest, I doubt that.
I bet not 1 in 25 jQuery developers know that $(callback) works. I certainly didn't until I read this (excellent) article, and it's not for lack of exposure to jQuery in the past 2-years.
So I don't think we can ascribe that to "lazy" developers at all. Quite the contrary.
How does that old-saying go, never ascribe to malice that which can be explained by incompetence? I think this is a case of that.
This leaves me wondering why $(callback) isn't more universally used, especially at the bespoke framewok-level. Something like this, enforcing synchronously dependent things, firing things in strictly defined sequence. Off-the-top-of-my-head:
$(loadFirst);
$(ajaxCalls); // deSerialize called therein as a callback
$(binding);
$(uiEffects);
$(wireEvents);
$(formValidation);
$(setNavigationState);
$(loadLast);
This beats the pants off $(function{...}) calls especially if you're pulling-things from various external files. If the jQuery invocations are logically structured and organized, quite a few potential gotchas go away.
Just saying, if more devs knew about $(callback), we'd be seeing *some* discussions along these lines.
**--** Steve
A few problems
You've got a problem in your example code:
In the first example
You don't need (or want) the angle brackets around the div. When used in this manner you're actually using the second usage jQuery(html, [ownerDocument]). Instead of a list of divs you'll get back a new div element that has been created for you. This does what you want.
Also, you didn't touch on the last usage jQuery( callback ). This just takes a function and calls it when the document is loaded and ready. Essentially it is equivalent to $(document).ready( callback ). So the following two code snippets do exactly the same thing.
Nice write up by the way. I rarely think about how bizarre jQuery must seem to new comers who aren't already comfortable with javascript.
Thanks for that, I'll make a
Thanks for that, I'll make a change to the post. You're also totally right about missing the call back, I had planned on doing that, but totally forgot, I'll revise the post and add it in.
Thanks for the comments and positive feed back :)
Syn