Week 02, Day 05.

What we covered today:

Javascript Libraries

What is a Library?

A collection of reusable methods for a particular purpose. You just reference a javascript file with a particular library in it - and away you go!

jQuery is the most common library...

Have a crack at these exercises.

jQuery

What is it?

An open source JavaScript library that simplifies the interaction between HTML and JavaScript. A Javascript library is collection of reusable methods for a particular purpose.

It was created by John Resig in 2005, and released in January of 2006.

Built in an attempt to simplify the existing DOM APIs and abstract away cross-browser issues.

Why pick jQuery?

  • Documented
  • Lots of libraries
  • Small-ish size (23kb)
  • Everything works in IE 6+, Firefox 2+, Safari 3+, Chrome, and Opera 9+ (if you are using 1.11.3 or previous, greater than that scraps up until IE8 support)
  • Millions and millions of sites using it. According to BuiltWith.com, 52,339,256 live sites are using it. 26.95% of sites apparently use it.

What does it do for us?

  • Data Manipulation
  • DOM Manipulation
  • Events
  • AJAX
  • Effects and Animation
  • HTML Templating
  • Widgets / Theming
  • Graphics / Chart
  • App Architecture

Why use it?

// No library:
var elems = document.getElementsByTagName("img");
for (var i = 0; i< elems.length; i++) {
  elems[i].style.display = "none";
}

// jQuery:
$('img').hide();

The Basics

Select -> Manipulate -> Admire

var $paragraphs = $("p")
$paragraphs.addClass('special');

// OR
$("p").addClass("special");

How to select things? All CSS selectors are valid, plus a whole heap more.

Some common ones are:

  • :first
  • :last
  • :has()
  • :visible
  • :hidden

Reading Elements

If we had this element in the HTML...

<a id="yahoo" href="http://www.yahoo.com" style="font-size:20px">Yahoo!</a>

We can select it using $("a#yahoo")

We can store it using var $myLink = $("#yahoo");

We can get the content within it using $("#yahoo").html()

We can get the text within it using $("#yahoo").text()

We can get the HREF attribute using $("#yahoo").attr("href")

We can get the CSS attribute using $("#yahoo").css('font-size')

Changing Elements

$("#yahoo").attr("href", "http://generalassemb.ly")

$("#yahoo").css("font-size", "25px")

$("#yahoo").text("General Assembly")

Create, Manipulate and Inject

// Step 1: Create element and store a reference
    var $para = $('<p></p>'); // You can create any element with this!

// Step 2: Use a method to manipulate (optional)
    $para.addClass('special'); // So many functions you could use

// Step 3: Inject into your HTML
    $('body').append($para); // Also could use prepend, prependTo or appendTo as well

Regular DOM Nodes to jQuery Objects

var $paragraphs = $('p'); // an array

var myParagraph = paragraphs[0]; // a regular DOM node

var $myParagraph = $( paragraphs[0] ); // a jQuery Object
// or
var $myParagraph = $paragraphs.el(0); // This is the preferred method!

// We can also loop through our array...
for( var i = 0; i < paragraphs.length; i++ ) {
   var element = paragraphs[i];
   var paragraph = $(element);
   paragraph.html(paragraph.html() + ' wowee!!!!');
};

// Or use jQuery to do it - this is preferred
$paragraphs.each(function () {
  var $this = $( this );
  $this.html( $this.html() + " wowee!!!" );
});

The Ready Event

$(document).ready(function(){

});

In order to do cool jQuery stuff, we need to make sure that all of the content so put all your DOM related jQuery code in the document ready.

Have a crack at these exercises.

Homework

This and this.

Events

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

$('button').on('click', onButtonClick); // Attaching an event handler with a defined function to the button

$('button').on('click', function () { // Attaching an event handler with an anonymous function to the button
  console.log('clicked!');
});

$('button').click(onButtonClick)

Other Event Types

  • Keyboard Events - 'keydown', 'keypress', 'keyup'
  • Mouse Events - 'click', 'mousedown', 'mouseup', 'mousemove'
  • Form Events - 'change', 'focus', 'blur'

Arguments get passed into callbacks by default.

var myCallback = function (event) {
    console.log( event );
    // The event parameter is a big object filled with ridiculous amounts of details about when the event occurred etc.
};

$('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 and Animations

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

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

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

jQuery Patterns and Anti-Patterns

// Pattern: name variables with $
var $myVar = $('#myNode');

// Pattern: bind events to the document or "body"
$("body").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
$("body").on('click', 'p', function(argument) {
  // do something anonymous
});

Chaining jQuery Functions

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();

Read here for more information

Have a crack at these exercises.

Plugins with jQuery

To Find Plugins

How to select a good plugin

  • Well documented
  • Flexible
  • Community
    • Number of forks and issues
  • Actively maintained?
  • File size
  • Browser compatibility
  • Responsive

For more details, go here.

How to use a plugin

  • Download the plugin and associated files from the site or Github repository
  • Copy them into your project folder
  • In the HTML, reference any associated CSS
  • After you reference jQuery, and before you reference your own code - add the script tag that references the plugins JS file(s)

Give this a go