- Basic jQuery Syntax Usage
- jQuery Core Capabilities
- Extending jQuery to Create Tabs
- Using Ajax to Fetch XML Data
- Summary
jQuery Core Capabilities
Understanding what you can do once you have a selection requires knowledge of jQuery's core capabilities. The excellent jQuery documentation goes into all the options, but I'll demonstrate and use a few here. First, the addClass() method adds a new class to the selected element(s). For example, in the AIR application, I want to apply a darkBlue class to every element that has a class of caption (CSS allows elements to have multiple classes). To make that happen, I define my class in CSS and then execute this jQuery line:
$('.caption').addClass('darkBlue');
The first part selects every element that has a class value of caption, the second part adds the darkBlue class to those elements. So the HTML page has this:
<td class="caption">First Name</td>
which jQuery effectively turns into the following:
<td class="caption" class="darkBlue">First Name</td>
This is a somewhat trivial example, but it shows how easy jQuery is to use, once you know its syntax and understand what's possible.
Another action you might take with document elements is assigning event handlers: something to be done if the user clicks an element, mouses over it, changes its value, and so on. If you look back at the application in Figures 1, 2, and 3, you'll see a button next to the More Information heading. When clicked, this button shows/hides the This is the message text message. In the HTML code, this button has an id value of messageButton:
<button id="messageButton">Show/Hide</button>
Next, in the setup function, the following bit of code associates the click event with the function to be called when that event occurs:
$('#messageButton').click(showHideMessage);
The name of the function, not in quotes and without parentheses, just needs to be provided as an argument to the click() method.
The showHideMessage() function is defined really easily, thanks to jQuery's toggle() method:
function showHideMessage(e) { $('#message').toggle('slow'); }
The toggle() method toggles the visibility of an element. It can be provided with a speed, such as slow or fast, instead of the default normal speed. So now, whenever the user clicks the button, the showHideMessage() is called. If the message is currently hidden, it will be revealed; if it's currently displayed, it will be hidden. It's that simple!