Basics of jquery

home

 

jquery is written in javascript, which means it is javascript, which means it runs client-side and can only do javascript things. One reason to use it is the commands are maintained to work with most browsers -- the jquery command for page size runs all of the "if(browser=FireFox3.2)"'s to do it the correct way for that browser. The other reason to use it are the apply-to-all commands. $("p.silly").click(...) makes it so all paragraphs with class silly perform that action on a click.

jquery is all in one file, jquery.js. You can get a copy and link to it:

<script type="text/javascript" src="jquery.js"></script>

But for real everyone uses jquery and no one needs to download your copy. Instead your webpage should link to jquery.js at some master site so that clients can say "oh, I already have that" and save time.

Here's some sample jquery. It's not super-useful since it finds the single item with ID #catTable1, and attaches an onmouseout event, which we could easily do outselves. But it can be anywhere:

$("#catTable1").mouseout(
  function() {
    $(this).css({'color' : 'black'});
  }
);

Explaining this from left to right: $() is a legal function name in javascript. Since it's short and distinctive, jquery stole it. $() is the main way to run jquery. Next, jquery borrows the #-sign from style-sheets to mean "item with this ID". Altogether, $("#catTable1") tells jquery to do something to <table id="catTable1">.

mouseout is jquery's version of onmouseout. It's being passed a made-just-now javascript function, since why not. Inside, $(this) is calling jquery again, on itself this time. css() is the jquery command to change to style-sheet rules, using the special jquery input style.

The above attached an event to one item. The more useful options are $(".silly") -- attach to everything of class silly (or $("p.silly") for only silly paragraphs), and $("p") for simply all paragraphs. Note how this copies style-sheet rules, where # is id, dot is class and "nothing" is that element type. Ex's:

// ID style (a single item gets big and purple on mouseover):
$("#p1").mouseover(function() { // pound-sign is ID
    $(this).css({'font-size' : 'larger', 'color' : '#ff00FF'});

// class style (all tagged items turn red on a click):
$(".redClick").click(function() { $(this).css({'color' : '#ff00FF'});

// element style (all paragraphs get have an info pop-up):
$("p").mouseover(function() { // no prefix means this is for every paragraph
  var pos = $(this).position();
  $("#float1").css({'left': pos.left+'px', 'top': pos.top+'px' }); // #float1 is that specific ID
})

As a bonus, a unquoted string is a by-id super-shortcut: $(catTable1) is a shortcut for $("#catTable1").

To find sub-items we get the jquery find command. It looks through all children: $("#catTable").find("td") affects all TD's inside of catTable1.

In theory all events should be attached inside a special ready, which fires after the page loads:

$(document).ready(function(){
  $("p").click( ..... );
    ...
}

Things you can do

css takes a hashmap with css style:value pairs. Note it uses the normal css names, not the camel-case javascript ones. Ex:

$(this).css({"background" : "blue", "border" : "2px solid green"});

Hiding and revealing an item: $(this).show() and $(".silly").hide().

text is a shortcut to both read and set text content: var w=$(this).text(); and $(this).text("replacement text here").. I'm not sure if it's the dangerous innerHtml or the safer innerText.

click adds a click event. Likewise mouseover and mouseout. Note how jquery removes the "on" (but obviously, internally it adds them using proper onclick and so on).

hover is a new jquery thing. It takes two functions, for enter and leave (it also doesn't have a delay like a real hover):

$("td").hover(
    function() { changeCol(this, "orange") }, // in
    function() { changeCol(this, "green") }    // out
);

focusin and focusout are for input items, like a textbox.

Alternate syntax for every event looks like $("p").on("click", ... );. It's an on and then the jquery event name in quotes.

empty() destroys all children, append(w) inserts as the last child and prepend(w) adds as the first child. A silly example replacing rows of a table with new ones:

$("#tab1").click(function() {  // assuming <table id="tab1">
  
  $(this).empty(); // clear all children (which means all rows in this case)
    
  // array pretending to be real input:
  var Items = []; // an empty array
  Items.push({"type":"sedan", "cost":"126"});
  Items.push({"type":"roadster", "cost":"85"});
    
  for(car of Items) { // "x of A" gets items, "x in A" gets 0,1,2 indexes
    
    // crude construction of each row:
    w="<tr> <td>"+car['type']+"</td><td>"+car['cost']+"</td> </tr>";
      
    $(this).append(w); // <- add to end of array
  }
  $(this).prepend("<tr><th>type</th><th>cost</th></tr>"; //  <- add headings to front
}

For controls which have an event (A's that follow a link, or SUBMIT buttons), their event runs after jquery's. jquery can cancel that with either event.preventDefault(); or simply return false;.

Reading from input fields

Values from text inputs and dropdowns are gettable with val():

// reading from text field and dropdown:
<p> <input type="text" id="jqtb1">

<select id="jqs1">
<option value="aa">Aa</option>
<option value="bb">Bb</option>
<option value="cc">Cc</option>
</select>

<script>
function jqInputTest0() {
  var b0=$(jqtb1).val(); // value of textbox
  var b1=$(jqs1).val(); // value of dropdown (the single selected box)
  $(jqInputTest0Out).text(b0+" "+b1); // results test
}
</script>

Checkbox groups use $("input[name=cbGroupName]:checked"), and return an array of the checked boxes (not merely the values, the html items):

<p>
<input type="checkbox" name="jqcb1" value="A">box a
<input type="checkbox" name="jqcb1" value="B">box b
</p>

<script>
function jqInputTest1() {
  var b2=$("input[name=jqcb1]:checked"); // array of all checked boxes
  var w=""
  for(var i=0; i<b2.length; i++) {
    w+="item: "+b2[i].value+" "; // <- pull out the value, using normal javascript
  }
  $(jqInputTest0Out).text(b2.length+" items: "+w);
}
</script>

misc

javascript and jquery can be freely mixed. Normal javascript can use jquery:

function changeCol(obj, newCol) {
  $(obj).css("color", newCol); //  jquery command
}

And jquery events can use normal javascript (to set styles, say):

$("p").mouseover(function() { // jquery event setting
  this.style.color="#FF00FF"; // javascript style setting
});