More jQuery

Events

var onButtonClick = function() {
  console.log('clicked!');
};

$('button').on('click', onButtonClick);

$('button').on('click', function () {
  console.log('clicked!');
});

$('button').click(onButtonClick)

Follow along: http://jsbin.com/dosewola/7/edit

Remember: Callbacks

Events


Arguments get applied in callbacks

var myCallback = function(event) {
	console.log(event);
};

$('p').on('mouseenter', myCallback);

Preventing Default Events

$('a').on('click', function (event) {
	event.preventDefault();
	console.log('Not going there!');
});
$('form').on('submit', function (event) {
	event.preventDefault();
	console.log('Not submitting, time to validate!');
});

Effects & Animation


$('#error').toggle(1000);

$('#error').fadeIn();

$('#error').show(1000, function(){
	$(this).addClass('redText')
});

Exercise Time!

click here!

jQuery Plugins


"If you want to create an animation, effect, or UI component, chances are pretty good that someone has done the work for you already."

plugins.jquery.com



Which plugin should you pick?

jQuery Plugin Usage

  • Download the plugin and associated files from the site or github repo.
  • Copy them into your project folder.
  • In the HTML, reference any associated CSS files.
  • <link rel="type/stylesheet" type="text/css" href="tablesorter.css">
  • In the HTML, add a <script> tag for the jQuery plugin itself.
  • <script src="lib/tablesorter.js"><script>
  • In the JavaScript, call the jQuery plugin on your DOM.
  • $('table').tableSorter();

Exercise Time!

click here!

jQuery Patterns and Anti-Patterns


Pattern: name variables with $

var $myVar = $('#myNode');


Pattern: bind events to the document

$(document).on('click', 'a', myCallback);

Storing References

Pattern: store references to callback functions

var myCallback = function(argument) {
  // do something cool
};

$(document).on('click', 'p', myCallback);

Anti-pattern: anonymous functions


$(document).on('click', 'p', function(argument) {
  // do something anonymous
});

Chaining


banner.css('color', 'red');
banner.html('Welcome!');
banner.show();

Is the same as:

banner.css('color', 'red').html('Welcome!').show();

Is the same as:

banner.css('color', 'red')
       .html('Welcome!')
       .show();

DOM Readiness

Broken code: DOM manipulation and event binding in the <head>

<head>
  <script>
    $('body').append( myNode );
  </script>
</head>

Pattern: If you need to load a script in the <head>, wait for the rest of the DOM to be ready before executing

<body>
  ...
  <script>
    $(document).ready(function() {
      // do something when the DOM is fully loaded
    });
  </script>
</body>

jQuery


...is great.

But do not become a jQuery-dependant!

jQuery


docs.jquery.com