Monday, August 23, 2010

Basic jQuery Scripts

The real trick to understanding jQuery is just getting the basics down. One thing that surprised me is how everything goes through a single function. The one function you use is called (drumroll please...) jQuery. This surprised me when I first started using this language. It kind of reminds me how in JAVA, everything descends from OBJECT.

Basically everything that is used within this jQuery function exists within what we call a NAMESPACE. This is a sandbox approach to handling code and makes sure that everybody plays fair and doesn't do things like overriding other people's functions.

Typically when you see a jQuery statement you will simply see the dollar sign: $. This is an alias that we can conveniently use to help shorten the length of our code. You can still use the full jQuery function like the example below:

jQuery('p').html('Basic jQuery statement');

$('p').html('Basic jQuery statement');

are both the same statement. However the later example saves us roughly 5 keystrokes so I prefer to just use the dollar sign $.

BASIC STATEMENT

$('p').html('Basic jQuery statement');

The example above is a basic jQuery statement. It has three components: a selector, action, and parameters. In this example the selector is $('p') which is selecting the paragraph tag <p></p> in the DOM (Document Object Model). The .html is the action which is applied to the element we selected (in this case the paragraph tag). In this example the action .html gets the HTML contents of the first element in the set of matched elements. The last part of the statement are the parameters which in this example is ('Basic jQuery statement'); which tells jQuery how to apply the action.

To summarize,  the statement above applies to the first paragraph tag and includes the text 'Basic jQuery statement' to it. Our example only passes one parameter but we can pass many more if we need to, depending on the type of action we use.

No comments:

Post a Comment