kuujinbo_dot_info

Why jQuery?

Updated 2009-07

jQuery is appealing because: (1) it uses CSS, XPath, and custom selectors to work it's magic, and (2) the API is very similar to Perl.

Getting Started

First load your jQuery code. Instead of:

window.onload = function(){ ... }

to start working with the document object model (DOM) and adding events, use the jQuery shortcut:

$(document).ready(function(){
  // your javascript code
});

Selectors

To select an element with plain Javascript:

var element = document.getElementById('ELEMENT_ID');
In jQuery
var element = $('ELEMENT_ID');

which actually creates a new jQuery object to work with. In this page we're using a single DIV container to show the updates, and DOM and CSS to display the results. Look through this page's HTML page source:

<div id='prototype_wrapper'
style='position:absolute;display:none;z-index:100;
width:240px;padding:1.0em 3px;border:1px solid #000
;background:#ffffcc;'>
<div id='jq_content'></div>
<div id='systemWorking'>
<img src='/kyouyuu/image/ajax-processing-small.gif'>
Loading...
</div>
</div>

Notes:

  • The first (outermost) DIV container is used to show/hide the results from the Ajax call on onmouseover/onmouseout.
  • The second DIV container holds the Ajax query results as HTML.
  • The third DIV container shows a status image to let the user know their request is being processed. For demonstration, the page processing the Ajax request has an explicit half-second Thread.Sleep() call to simulate a long running process.

Javascript jQuery Style

Now we can get to the jQuery. To work with the three DIV containers above we create a new jQuery object for each using the jQuery selector:

var jq_wrapper = $('#jq_wrapper');
var jq_content = $('#jq_content');
var jq_working = $('#systemWorking');
We definitely want to make sure any error conditions ( ajaxError() ) are handled and show a friendly message to the client:
jq_content.ajaxError(function(request, settings) {
  $(this).html('<span class="red">Error requesting page');
});
To give the client an indication the page is loading on long running processes, we use the ajaxStart() method to bind the function that shows the spinning gif when the AJAX request begins, and the ajaxStop() method to bind the function that hides the spinning gif when all AJAX requests have ended:
jq_working.ajaxStart(function(){
  jq_content.hide();
  $(this).show();
});
jq_working.ajaxStop(function(){
  $(this).hide();
  jq_content.show();
});

Positioning the Data

jQuery saves you a ton of work trying to get the height/width and top/left offset of any element that is cross-browser compliant. Since we want the query results positioned near the hyperlink, that's exactly what we need:

var cur_dim = $(this).offset();
var win_h = $(window).height();
var win_w = $(window).width();
var this_h = cur_dim.top;
var this_w = cur_dim.left;
var ctop  = win_h / 2 >= this_h ? this_h : this_h - 50;
var cleft = win_w / 2 >= this_w
  ? this_w + $(this).width()
  : this_w - jq_wrapper.width() - $(this).width();

Ajax Call

The calculations above will be used in the function body used for the mouseover event that does the Ajax call:

// jQuery selector; hyperlinks with 'class' attribute set to 'jq_tt'
$('a.jq_tt').mouseover(function() {
  jq_wrapper.show();  // show Ajax response results
  /* top/left calculation code above goes here */
  // and set here
  jq_wrapper.css( {top:ctop, left:cleft} );
  // Ajax request/response processing
  jq_content.load($(this).attr('href'),
    function(responseText, stat, response) {
      // only show **successful** responses; our error handler above
      // will show a friendly message otherwise
      if (stat == 'success') {
        jq_content.html(responseText);
      }
    }
  );
});

Notes:

  • DO use the load() method if you are returning HTML. Although the documentation doesn't specify it, I found out the hard way that the paramaters passed determine whether POST/GET data is sent. (pass a hashmap as the second parameter for POST)
  • Yes, that means I also wasted a bit of time first trying to use the ajaxSend() method to dump HTML into the DIV container showing the query results. The problem is that ajaxSend() is working with XML, not HTML, and will dump the responseText text value. (stripping all tags)

All that's left is to hide the results on mouseout:

$('a.jq_tt').mouseout(function() {
  jq_wrapper.hide();
});

The results:

NoNameCityStateBornDied
1George Washington WakefieldVAFeb 22, 1732Dec 14, 1799
2John Adams BraintreeMAOct 30, 1735Jul 04, 1826
3Thomas Jefferson Albemarle CountyVAApr 13, 1743Jul 04, 1826
4James Madison Port ConwayVAMar 16, 1751Jun 28, 1836
5James Monroe Westmoreland CountyVAApr 28, 1758Jul 04, 1831
6John Quincy Adams BraintreeMAJul 11, 1767Feb 23, 1848
7Andrew Jackson Waxhaw settlementSCMar 15, 1767Jun 08, 1845
8Martin Van Buren KinderhookNYDec 05, 1782Jul 24, 1862
9William H. Harrison BerkeleyVAFeb 09, 1773Apr 04, 1841
10John Tyler GreenwayVAMar 29, 1790Jan 18, 1862
11James K. Polk PinevilleNCNov 02, 1795Jun 15, 1849
12Zachary Taylor Orange CountyVANov 24, 1784Jul 09, 1850
13Millard Fillmore LockeNYJan 07, 1800Mar 08, 1874
14Franklin Pierce HillsboroNHNov 23, 1804Oct 08, 1869
15James Buchanan MercersburgPAApr 23, 1791Jun 01, 1868
16Abraham Lincoln HodgenvilleKYFeb 12, 1809Apr 15, 1865
17Andrew Johnson RaleighNCDec 29, 1808Jul 31, 1875
18Ulysses S. Grant Point PleasantOHApr 27, 1822Jul 23, 1885
19Rutherford B. Hayes DelawareOHOct 04, 1822Jan 17, 1893
20James A. Garfield OrangeOHNov 19, 1831Sep 19, 1881
21Chester A. Arthur FairfieldVTOct 05, 1829Nov 18, 1886
22Grover Cleveland CaldwellNJMar 18, 1837Jun 24, 1908
23Benjamin Harrison North BendOHAug 20, 1833Mar 13, 1901
24William McKinley NilesOHJan 29, 1843Sep 14, 1901
25Theodore Roosevelt New YorkNYOct 27, 1858Jan 06, 1919
26William H. Taft CincinnatiOHSep 15, 1857Mar 08, 1930
27Woodrow Wilson StauntonVADec 19, 1856Feb 03, 1924
28Warren G. Harding Blooming GroveOHNov 02, 1865Aug 02, 1923
29Calvin Coolidge Plymouth NotchVTJul 04, 1872Jan 05, 1933
30Herbert C. Hoover West BranchIAAug 10, 1874Oct 20, 1964
31Franklin D. Roosevelt Hyde ParkNYJan 30, 1882Apr 12, 1945
32Harry S Truman LamarMOMay 08, 1884Dec 26, 1972
33Dwight D. Eisenhower DenisonTXOct 14, 1890Mar 28, 1969
34John F Kennedy BrooklineMAMay 29, 1917Nov 22, 1963
35Lyndon B. Johnson StonewallTXAug 27, 1908Jan 22, 1973
36Richard M Nixon Yorba LindaCAJan 09, 1913Apr 22, 1994
37Gerald R Ford OmahaNEJul 14, 1913Dec 26, 2006
38James E. Carter Jr.PlainsGAOct 01, 1924
39Ronald W. Reagan TampicoILFeb 06, 1911Jun 05, 2004
40George H.W. Bush MiltonMAJun 12, 1924
41William J. Clinton HopeARAug 19, 1946
42George W. Bush New HavenCTJul 06, 1946

jQuery Links