JQuery – Syntax Cheat Sheet

Document Setup

Linking the document
<script src="script.js" type="text/javascript"></script>

Getting Started
Next, we’ll need to start up our jQuery magic using the $(document).ready(); syntax you’ve seen. It works like this:

  • $() says, “hey, jQuery things are about to happen!”
  • Putting document between the parentheses tells us that we’re about to work our magic on the HTML documentĀ itself.
  • .ready(); is a function, or basic action, in jQuery. It says “hey, I’m going to do stuff as soon as the HTML document is ready!”
  • Whatever goes in .ready()‘s parentheses is the jQuery event that occurs as soon as the HTML document is ready.

Function
Put something inside our ready() function.

Remember, when we say “function,” you can think “action.” Functions are the basic unit of doing work in jQuery.

For this reason, jQuery includes a function keyword. The syntax looks like this:

function(){
  jQuery magic;
}

If we add our function inside our .ready(), jQuery will run the code in our function as soon as the HTML document loads. The syntax would then look like this:

$(document).ready(function() {
  jQuery magic;
});

Action
Between the {}s of our function(), we’ll want to turn our div into a jQuery object so jQuery can manipulate it.

Example 1:

$(document).ready(function() {
  $('div').action(howfast);
});

Example 2:

$(document).ready(function() {
  $('div').mouseenter(function() {
    $('div').hide();
  });
});

Code Samples
Fade on mouse enter

$(document).ready(function() {
  $('div').mouseenter(function () {
    $('div').fadeTo('fast', 1);
  });
});

Fade on mouseenter and fade on mouseleave

$(document).ready(function() {
  $('div').mouseenter(function () {
    $('div').fadeTo('fast', 1);
  });
  $('div').mouseleave(function () {
    $('div').fadeTo('fast', .5);
  });
});