alt
Advertisement
Sponsored links
Online Training
Career Series
Exforsys
Exforsys arrow Tutorials arrow jQuery arrow jQuery Reference
Site Search


jQuery Reference
Article Index
jQuery Reference
Writing the jQuery Code
DOM Traversal Methods
AJAX Methods

Writing the jQuery Code

Our custom code will go in the second, currently empty, JavaScript file which we included from the HTML using <script src="dolittle.js" type="text/ javascript"></script>. Despite how much it accomplishes, the script is fairly short:

  1. jQuery.fn.toggleNext = function() {
  2. this.toggleClass('arrow-down')
  3. .next().slideToggle('fast');
  4. };
  5. $(document).ready(function() {
  6. $('<div id="page-contents"></div>')
  7. .prepend('<h3>Page Contents</h3>')
  8. .append('<div></div>')
  9. .prependTo('body');
  10. $('#content h2').each(function(index) {
  11. var $chapterTitle = $(this);
  12. var chapterId = 'chapter-' + (index + 1);
  13. $chapterTitle.attr('id', chapterId);
  14. $('<a></a>').text($chapterTitle.text())
  15. .attr({
  16. 'title': 'Jump to ' + $chapterTitle.text(),
  17. 'href': '#' + chapterId
  18. })
  19. .appendTo('#page-contents div');
  20. });
  21. $('#page-contents h3').click(function() {
  22. $(this).toggleNext();
  23. });
  24. $('#introduction > h2 a').click(function() {
  25. $('#introduction').load(this.href);
  26. return false;
  27. });
  28. });
 
We now have a dynamic table of contents that brings users to the relevant portion of the text, and an introduction that is loaded on demand.

Script Dissection

NOTE: We will not discuss the operation of this script in much detail here, but a similar script is presented as a tutorial on the Learning jQuery web log: http://www.learningjquery.com/2007/06/ automatic-page-contents.

Selector Expressions

Before we can act on an HTML document, we need to locate the relevant portions. In our script, we sometimes use a simple approach to finding an element:

$('#introduction')

This expression creates a new jQuery object that references the element with the ID introduction. On the other hand, sometimes we require a more intricate selector:

$('#introduction > h2 a')

Here we produce a jQuery object potentially referring to many elements. Elements are included if they are anchor tags, but only if they are descendants of <h2> elements that are themselves children of an element with the ID introduction.

These selector expressions can be as simple or complex as we need. Chapter 2 will enumerate all of the selectors available to us and how they can be combined.



 
< Prev   Next >
Exforsys Offers
© 2008 Exforsys.com
Joomla! is Free Software released under the GNU/GPL License.
Page copy protected against web site content infringement by Copyscape