Basics of jquery

home

 

jquery is written in javascript. It is javascript. It's one extra file, defining some functions. Your javascript code can call them, or they can call regular javascript code. To get jquery, simply link to the single file: jquery.js:

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

For real, people link to one stored on various master sites. That might seem messy, but the theory is that since jquery is so common, everyone using your site already has a copy on their computer.

Like javascript, jquery lives on the web page and can only do things javascript can do. If offers a few shortcut commands. But the main advantage is the commands are maintained to work with most browsers (if you've used javascript and css, major browsers work differently, as do older versions, and the documentation isn't even correct). The other special thing is the way it allows apply-to-all commands. For example $("p.silly") applies to every paragraph with class silly (<p class="silly">).

Unlike javascript, actions aren't written inside of the tags they affect. Instead, you write code, anywhere, which attaches your jquery events to things on the page. These events are allowed to use this, as usual, to talk about whatever they're attached to. This attaches a click event to catTable1 (<table id="catTable1">):

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

A neat thing is you can mass-attach your event. You can attach to a single item, using "#ID", or to everything in an html class with ".className" or everything with a tag using it naked: "h1":

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

// anything with class redClick turns red on a click:
$(".redClick").click(function() { $(this).css({'color' : '#ff00FF'});

// all paragraphs get the single item with ID="float1" moved on them during a mouseover:
$("p").mouseover(function() {
  var pos = $(this).position();
  $("#float1").css({'left': pos.left+'px', 'top': pos.top+'px'});

The find command works in a similar sneaky way. It looks through all children and affects all of them meeting the condition. $("#catTable").find("td") affects all table descriptions inside of cat table 1.

In theory, you should attach all events in an official jquery ready, which fires after the page loads:

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

You can write as many of these as you like, spaced anywhere in the page.

Actions

Basic format is $("#itemID).ACTION( doThis );. Some actions are:

An alternate syntax uses dot-on for them all: $("p").on("click", ...);

Things you can do

Any standard css change can be done with dot-css, then the style:attribute in curlies. Use the normal css names, not the camel-case javascript ones:

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

Shortcuts for hiding and revealing an item: ($this).show() and ($this).dot-hide().

Shortcut to read and set text content: var w=($this).text(); and ($this).text("replacement text here")..

Items can be destroyed and added. Commands are empty) (destroy all children), append(w) (insert as last child) and prepend(w) (add as first child). In most cases show/hide is better, but this is good if, say, you want to replace a table with new items: delete the content and add all fresh rows. Here, I'll use a fake array pretending to be the rows from some query:

$("#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
}

Obviously, these are good for "containers" like UL or TABLE or DIV. But you can put things inside a paragraph if you want.

Cancel a normal action (follow a link, submit a form) with either event.preventDefault(); or simply return false;.

Javascript Review

Remember that javascript doesn't have formal classes. An object is, python-like, just a hashmap from strings to anything. p.cat=5 is a shortcut for p['cat']=5. { "color" : "red" } is an anonymous object with o.cat="red". When you pass an arbitrary object, it can be read with: for(p in obj). p will hold the name of the property, and fetching the value uses obj[p].

More javascript review: since objects don't have types, and don't have preset fields, a "class" is defined by one (or more) functions which double as constructors. new runs any normal function which uses this to set fields:

function petsMaker(x,y) { this.cat=x; this.dog=y; }

var p1 = new petsMaker(3,5); // {cat:3, dog:5}

jquery can call regular javascript functions, and javascript functions can use jquery commands:

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

$("p").mouseover(function() { // jquery "attach" command
    changeCol(this, "green"); // calling a regular javascript function
});